Added Prompt for tools (#68)

* Create detailed markdown instructions for all toolkits
* Update all toolkit classes to load instructions from external .md files
* Add query examples for cryptocurrency report generation
This commit was merged in pull request #68.
This commit is contained in:
Simo
2025-10-31 00:13:02 +01:00
committed by GitHub
parent df14ae5bc6
commit c501a58bf4
17 changed files with 1115 additions and 59 deletions

538
docs/Query_Examples.md Normal file
View File

@@ -0,0 +1,538 @@
# Query Examples - Cryptocurrency Report Generation
This document provides examples of user queries that trigger specific tools in the cryptocurrency analysis application.
## Table of Contents
- [CryptoSymbolsTools - Symbol Resolution](#1-cryptosymbolstools---symbol-resolution)
- [MarketAPIsTool - Price & Historical Data](#2-marketapistool---price--historical-data)
- [NewsAPIsTool - News & Sentiment](#3-newsapistool---news--sentiment)
- [SocialAPIsTool - Social Media Sentiment](#4-socialapistool---social-media-sentiment)
- [PlanMemoryTool - Task Management](#5-planmemorytool---task-management)
- [ReasoningTools - Cognitive Analysis](#6-reasoningtools---cognitive-analysis)
- [Composite Queries - Multiple Tools](#7-composite-queries---multiple-tools)
- [Keyword Triggers Reference](#keyword-triggers---quick-reference)
---
## 1. CryptoSymbolsTools - Symbol Resolution
### `get_symbols_by_name(query)` - Resolve cryptocurrency names to symbols
**Purpose:** Convert user-friendly names to trading symbols before calling market APIs.
**Example Queries:**
- ❓ "Dammi il prezzo di **Ethereum**"
- → Searches "ethereum" → Finds "ETH-USD"
- ❓ "Analizza **Solana** e **Cardano**"
- → Resolves both names to SOL-USD, ADA-USD
- ❓ "Quanto vale **Dogecoin**?"
- → Searches "dogecoin" → Finds "DOGE-USD"
- ❓ "Confronta **Bitcoin** e **Bitcoin Cash**"
- → Handles ambiguity (2 matches: BTC-USD, BCH-USD)
- ❓ "Report su **Polkadot**"
- → Resolves to "DOT-USD"
**Trigger Words:** Cryptocurrency common names (Bitcoin, Ethereum, Solana, etc.)
---
### `get_all_symbols()` - List all available cryptocurrencies
**Purpose:** Verify symbol availability or show complete list.
**Example Queries:**
- ❓ "Quali criptovalute sono disponibili?"
- ❓ "Mostrami tutte le crypto supportate"
- ❓ "Lista completa delle criptovalute"
- ❓ "Esiste **XYZ-USD** nel sistema?"
- → Verifies if symbol exists in list
**Trigger Words:** "disponibili", "supportate", "lista", "tutte", "esiste"
---
## 2. MarketAPIsTool - Price & Historical Data
### Single-Source Tools (FAST - First available provider)
#### `get_product(asset_id)` - Current price for single asset
**Purpose:** Quick price check for one cryptocurrency.
**Example Queries:**
- ❓ "Qual è il prezzo attuale di Bitcoin?"
- ❓ "Quanto vale BTC adesso?"
- ❓ "Prezzo corrente di Ethereum"
- ❓ "Valore di SOL?"
- ❓ "Quotazione Cardano"
**Trigger Words:** "prezzo", "quanto vale", "valore", "quotazione", "attuale", "corrente", "adesso"
---
#### `get_products(asset_ids)` - Current prices for multiple assets
**Purpose:** Quick price comparison of multiple cryptocurrencies.
**Example Queries:**
- ❓ "Dammi i prezzi di BTC, ETH e SOL"
- ❓ "Confronta i valori di Bitcoin, Ethereum e Cardano"
- ❓ "Lista prezzi: BTC, DOGE, ADA"
- ❓ "Prezzi attuali delle top 5 crypto"
- ❓ "Quanto valgono Bitcoin ed Ethereum?"
**Trigger Words:** Multiple assets mentioned, "confronta", "lista prezzi", "valori di"
---
#### `get_historical_prices(asset_id, limit)` - Historical data for single asset
**Purpose:** Price history and trend analysis.
**Example Queries:**
- ❓ "Prezzo di Bitcoin negli ultimi 7 giorni"
- ❓ "Storico di ETH dell'ultimo mese"
- ❓ "Come è variato Solana nelle ultime 24 ore?"
- ❓ "Andamento BTC ultima settimana"
- ❓ "Grafico storico di Ethereum"
**Trigger Words:** "storico", "ultimi N giorni/ore", "ultimo mese", "variato", "andamento", "trend", "grafico"
**Time Range Mapping:**
- "ultime 24 ore" / "oggi" → limit=24 (hourly) or limit=1 (daily)
- "ultimi 7 giorni" / "ultima settimana" → limit=7
- "ultimo mese" / "ultimi 30 giorni" → limit=30
- "ultimi 3 mesi" → limit=90
---
### Aggregated Tools (COMPREHENSIVE - All providers with VWAP)
#### `get_product_aggregated(asset_id)` - Accurate price from all sources
**Purpose:** Most reliable price using Volume Weighted Average Price (VWAP) from all providers.
**Example Queries:**
- ❓ "Dammi il prezzo **più accurato** di Bitcoin"
- ❓ "Qual è il prezzo **affidabile** di ETH?"
- ❓ "Voglio il prezzo di BTC da **tutte le fonti**"
- ❓ "Prezzo **preciso** di Solana"
- ❓ "Prezzo **verificato** di Cardano"
**Trigger Words:** "accurato", "affidabile", "preciso", "verificato", "tutte le fonti", "completo", "da tutti i provider"
---
#### `get_products_aggregated(asset_ids)` - Accurate prices for multiple assets
**Purpose:** Comprehensive multi-asset analysis with aggregated data.
**Example Queries:**
- ❓ "Analisi **dettagliata** dei prezzi di BTC ed ETH"
- ❓ "Confronto **completo** tra Bitcoin e Ethereum"
- ❓ "Report **comprensivo** su BTC, ETH, SOL"
- ❓ "Dati **affidabili** per top 3 crypto"
- ❓ "Prezzi **aggregati** di Bitcoin e Cardano"
**Trigger Words:** "dettagliata", "completo", "comprensivo", "affidabili", "aggregati" + multiple assets
---
#### `get_historical_prices_aggregated(asset_id, limit)` - Historical data from all sources
**Purpose:** Complete historical analysis with data from all providers.
**Example Queries:**
- ❓ "Storico **completo** di Bitcoin da tutte le fonti"
- ❓ "Analisi **comprensiva** del prezzo di ETH nell'ultimo mese"
- ❓ "Dati storici **affidabili** di BTC"
- ❓ "Andamento **dettagliato** di Solana ultimi 7 giorni"
- ❓ "Trend **aggregato** di Cardano"
**Trigger Words:** "storico completo", "comprensiva", "affidabili", "dettagliato", "aggregato" + time range
---
## 3. NewsAPIsTool - News & Sentiment
### Single-Source Tools (FAST - First available provider)
#### `get_top_headlines(limit)` - Top cryptocurrency news
**Purpose:** Quick overview of current crypto news headlines.
**Example Queries:**
- ❓ "Quali sono le ultime notizie crypto?"
- ❓ "Dammi i titoli principali sulle criptovalute"
- ❓ "Cosa dicono le news oggi?"
- ❓ "Notizie del giorno crypto"
- ❓ "Ultime breaking news Bitcoin"
**Trigger Words:** "notizie", "news", "titoli", "ultime", "del giorno", "breaking"
**Limit Guidelines:**
- Quick scan: limit=5-10
- Standard: limit=20-30
- Deep research: limit=50-100
---
#### `get_latest_news(query, limit)` - News on specific topic
**Purpose:** Search for news articles about specific crypto topics or events.
**Example Queries:**
- ❓ "Notizie su **Bitcoin ETF**"
- ❓ "Cosa si dice del **crollo di Ethereum**?"
- ❓ "Trova articoli sulla **regolamentazione crypto**"
- ❓ "News su **DeFi security**"
- ❓ "Articoli su **NFT trends**"
- ❓ "Cosa dicono delle **whale movements**?"
**Trigger Words:** "notizie su", "articoli su", "cosa si dice", "trova", "cerca" + specific topic
**Query Formulation Tips:**
- User: "Bitcoin regulation" → query="Bitcoin regulation"
- User: "ETH price surge" → query="Ethereum price increase"
- User: "Crypto market crash" → query="cryptocurrency market crash"
---
### Aggregated Tools (COMPREHENSIVE - All news providers)
#### `get_top_headlines_aggregated(limit)` - Headlines from all sources
**Purpose:** Complete news coverage from all configured providers (NewsAPI, Google News, CryptoPanic, DuckDuckGo).
**Example Queries:**
- ❓ "Dammi le notizie crypto da **tutte le fonti**"
- ❓ "Panoramica **completa** delle news di oggi"
- ❓ "Cosa dicono **tutti i provider** sulle crypto?"
- ❓ "Confronta le notizie da **diverse fonti**"
- ❓ "Headline **aggregate** crypto"
**Trigger Words:** "tutte le fonti", "completa", "tutti i provider", "diverse fonti", "aggregate", "panoramica"
---
#### `get_latest_news_aggregated(query, limit)` - Topic news from all sources
**Purpose:** Comprehensive research on specific topic from all news providers.
**Example Queries:**
- ❓ "Ricerca **approfondita** su Bitcoin regulation"
- ❓ "Analisi **completa** delle notizie su Ethereum merge"
- ❓ "**Tutte le fonti** su NFT trends"
- ❓ "Confronto notizie da **tutti i provider** su DeFi"
- ❓ "Report **comprensivo** news Bitcoin ETF"
**Trigger Words:** "approfondita", "completa", "tutte le fonti", "tutti i provider", "comprensivo", "ricerca"
---
## 4. SocialAPIsTool - Social Media Sentiment
### Single-Source Tool (FAST - First available platform)
#### `get_top_crypto_posts(limit)` - Top social media posts
**Purpose:** Quick snapshot of social media sentiment on crypto.
**Example Queries:**
- ❓ "Cosa dice la gente sulle crypto?"
- ❓ "Sentiment sui social media per Bitcoin"
- ❓ "Discussioni trending su Reddit/Twitter"
- ❓ "Qual è il mood della community?"
- ❓ "Post popolari su crypto oggi"
- ❓ "Cosa dicono gli utenti di Ethereum?"
**Trigger Words:** "cosa dice", "sentiment", "discussioni", "mood", "community", "social", "Reddit", "Twitter"
**Limit Guidelines:**
- Quick snapshot: limit=5 (default, posts are long)
- Standard: limit=10-15
- Deep analysis: limit=20-30
---
### Aggregated Tool (COMPREHENSIVE - All platforms)
#### `get_top_crypto_posts_aggregated(limit_per_wrapper)` - Posts from all platforms
**Purpose:** Complete social sentiment analysis across Reddit, X/Twitter, and 4chan.
**Example Queries:**
- ❓ "Sentiment su **tutte le piattaforme** social"
- ❓ "Confronta Reddit e Twitter su Bitcoin"
- ❓ "Analisi **completa** delle discussioni social"
- ❓ "Cosa dicono **tutti** (Reddit, Twitter, 4chan)?"
- ❓ "Panoramica **social aggregate** su crypto"
- ❓ "Mood su **tutte le piattaforme** crypto"
**Trigger Words:** "tutte le piattaforme", "confronta", "completa", "tutti", "aggregate", "panoramica"
---
## 5. PlanMemoryTool - Task Management
**Note:** This tool is used **internally** by the Team Leader agent. Users don't call it directly, but complex queries trigger automatic task planning.
### Automatic Triggering by Query Complexity
#### Simple Query (1-2 tasks):
- ❓ "Prezzo di Bitcoin"
- → Creates 1 task: "Fetch BTC price"
- ❓ "Notizie su Ethereum"
- → Creates 1 task: "Get Ethereum news"
#### Complex Query (3+ tasks):
- ❓ "**Report completo** su Bitcoin"
- → Creates 3 tasks:
1. "Fetch BTC-USD current price and historical data"
2. "Analyze Bitcoin news sentiment (last 24h, limit=20)"
3. "Check Bitcoin social discussions (limit=10)"
- ❓ "Analizza il mercato crypto oggi"
- → Creates multiple tasks:
1. "Get top crypto prices (BTC, ETH, SOL, ADA)"
2. "Get crypto news headlines (limit=30)"
3. "Check social sentiment on crypto market"
**Trigger Words for Complex Queries:** "report completo", "analisi completa", "analizza", "studio", "ricerca approfondita"
---
## 6. ReasoningTools - Cognitive Analysis
**Note:** This tool is used **internally** by the Team Leader for decision-making. Triggered automatically during complex operations.
### `think()` - Step-by-step reasoning
**Automatic Triggers:**
- **Ambiguous Query:** "Bitcoin" → think: "Could be BTC or BCH, need to verify with CryptoSymbolsTools"
- **Strategy Decision:** Query with "accurate" → think: "User wants reliable data, should use aggregated tools"
- **Retry Strategy:** API failed → think: "Timeout error, should retry with broader parameters"
### `analyze()` - Result evaluation
**Automatic Triggers:**
- **After MarketAgent response:** → analyze: "Fresh data, high volume, proceed to next task"
- **After API failure:** → analyze: "API timeout, retry with modified parameters"
- **Before final report:** → analyze: "All 3 data sources complete, data quality high, generate comprehensive report"
---
## 7. Composite Queries - Multiple Tools
### Full Analysis Queries (Trigger ALL tools)
#### Query: **"Report completo su Bitcoin"**
**Tools Triggered:**
1. **CryptoSymbolsTools**: `get_symbols_by_name("bitcoin")` → "BTC-USD"
2. **MarketAPIsTool**: `get_products_aggregated(["BTC-USD"])`
3. **NewsAPIsTool**: `get_latest_news_aggregated("Bitcoin", limit=20)`
4. **SocialAPIsTool**: `get_top_crypto_posts_aggregated(limit=10)`
5. **PlanMemoryTool**: Creates 3 tasks, tracks execution, stores results
6. **ReasoningTools**: Think/analyze for each decision and synthesis
**Expected Output:** Comprehensive report with price data, sentiment analysis, social trends, and metadata.
---
#### Query: **"Confronta Bitcoin ed Ethereum: prezzi, news e sentiment"**
**Tools Triggered:**
1. **CryptoSymbolsTools**:
- `get_symbols_by_name("bitcoin")` → BTC-USD
- `get_symbols_by_name("ethereum")` → ETH-USD
2. **MarketAPIsTool**: `get_products(["BTC-USD", "ETH-USD"])`
3. **NewsAPIsTool**:
- `get_latest_news("Bitcoin", limit=20)`
- `get_latest_news("Ethereum", limit=20)`
4. **SocialAPIsTool**: `get_top_crypto_posts(limit=20)` → filter for BTC/ETH mentions
5. **PlanMemoryTool**: Creates 6 tasks (2 assets × 3 data types)
6. **ReasoningTools**: Compare and synthesize findings between BTC and ETH
**Expected Output:** Side-by-side comparison report with price differences, sentiment comparison, and cross-analysis.
---
#### Query: **"Come è cambiato Bitcoin nell'ultima settimana? Analizza prezzo, news e social"**
**Tools Triggered:**
1. **CryptoSymbolsTools**: `get_symbols_by_name("bitcoin")` → BTC-USD
2. **MarketAPIsTool**: `get_historical_prices("BTC-USD", limit=7)`
3. **NewsAPIsTool**: `get_latest_news("Bitcoin", limit=30)` → filter last 7 days
4. **SocialAPIsTool**: `get_top_crypto_posts(limit=20)` → filter last 7 days
5. **PlanMemoryTool**: Creates tasks for fetch + trend analysis
6. **ReasoningTools**: Analyze correlation between price changes and sentiment trends
**Expected Output:** Temporal analysis report showing price evolution, news sentiment over time, and social mood changes.
---
### Multi-Asset Analysis
#### Query: **"Report sui prezzi delle top 5 crypto con analisi di mercato"**
**Tools Triggered:**
1. **CryptoSymbolsTools**: Resolve top 5 crypto names to symbols
2. **MarketAPIsTool**: `get_products_aggregated(["BTC-USD", "ETH-USD", "SOL-USD", "ADA-USD", "DOT-USD"])`
3. **NewsAPIsTool**: `get_top_headlines(limit=50)` → extract relevant news for each
4. **SocialAPIsTool**: `get_top_crypto_posts_aggregated(limit=15)` → categorize by asset
5. **PlanMemoryTool**: Manages multi-asset task orchestration
6. **ReasoningTools**: Cross-asset comparison and market overview synthesis
---
### Focused Deep Dive
#### Query: **"Ricerca approfondita su Ethereum: storico 30 giorni, tutte le news, sentiment social completo"**
**Tools Triggered:**
1. **CryptoSymbolsTools**: `get_symbols_by_name("ethereum")` → ETH-USD
2. **MarketAPIsTool**: `get_historical_prices_aggregated("ETH-USD", limit=30)`
3. **NewsAPIsTool**: `get_latest_news_aggregated("Ethereum", limit=100)`
4. **SocialAPIsTool**: `get_top_crypto_posts_aggregated(limit_per_wrapper=30)`
5. **PlanMemoryTool**: Sequential execution with data validation
6. **ReasoningTools**: In-depth analysis with trend identification
**Expected Output:** Extensive Ethereum report with 30-day price chart, comprehensive news analysis, and detailed social sentiment breakdown.
---
## Keyword Triggers - Quick Reference
| Keyword / Phrase | Tool / Function | Type |
|------------------|-----------------|------|
| **Price-related** |
| "prezzo", "quanto vale", "valore", "quotazione" | `get_product()` | Market - Single |
| "prezzi di [list]", "confronta prezzi" | `get_products()` | Market - Single |
| "accurato", "affidabile", "tutte le fonti", "preciso" | `get_product_aggregated()` | Market - Aggregated |
| "storico", "ultimi N giorni", "variazione", "trend" | `get_historical_prices()` | Market - Historical |
| "storico completo", "dati aggregati storici" | `get_historical_prices_aggregated()` | Market - Historical Agg |
| **News-related** |
| "notizie", "news", "articoli", "titoli" | `get_top_headlines()` | News - Single |
| "notizie su [topic]", "articoli su [topic]" | `get_latest_news()` | News - Single |
| "tutte le fonti news", "panoramica completa news" | `get_top_headlines_aggregated()` | News - Aggregated |
| "ricerca approfondita", "tutti i provider" | `get_latest_news_aggregated()` | News - Aggregated |
| **Social-related** |
| "sentiment", "cosa dice la gente", "mood", "community" | `get_top_crypto_posts()` | Social - Single |
| "tutte le piattaforme", "Reddit e Twitter", "social completo" | `get_top_crypto_posts_aggregated()` | Social - Aggregated |
| **Comprehensive** |
| "report completo", "analisi completa" | ALL tools | Comprehensive |
| "ricerca approfondita", "studio dettagliato" | ALL tools | Comprehensive |
| "confronta [A] e [B]", "differenza tra" | Multiple assets | Comparison |
| **Symbol Resolution** |
| "Bitcoin", "Ethereum", "Solana" (names not symbols) | `get_symbols_by_name()` | Symbol Lookup |
| "disponibili", "lista crypto", "supportate" | `get_all_symbols()` | Symbol List |
---
## Best Practices for Query Formulation
### For Users:
1. **Be Specific About Scope:**
- ✅ "Prezzo accurato di Bitcoin da tutte le fonti"
- ❌ "Bitcoin" (ambiguous)
2. **Use Time Ranges When Relevant:**
- ✅ "Storico di Ethereum ultimi 30 giorni"
- ❌ "Storico Ethereum" (unclear timeframe)
3. **Specify Data Completeness Needs:**
- ✅ "Report completo su Solana con news e social"
- ❌ "Info su Solana" (unclear what data needed)
4. **Use Common Cryptocurrency Names:**
- ✅ "Analisi Bitcoin ed Ethereum"
- ✅ "Confronta BTC e ETH" (both work)
### For Team Leader Agent:
1. **Always Use CryptoSymbolsTools First:**
- When user mentions names, resolve to symbols before market calls
2. **Choose Single vs Aggregated Based on Keywords:**
- "accurato", "affidabile", "completo" → Use aggregated
- Quick queries without qualifiers → Use single-source
3. **Create Descriptive Tasks:**
- ✅ "Fetch BTC-USD price from Binance (aggregated, VWAP)"
- ❌ "Get price" (too vague)
4. **Use ReasoningTools Before Decisions:**
- Before choosing tool variant
- Before retry strategies
- Before final synthesis
---
## Time Range Reference
| User Expression | Limit Parameter | Time Period |
|----------------|-----------------|-------------|
| "oggi", "ultime 24 ore" | limit=1 or 24 | 1 day |
| "ultimi 7 giorni", "ultima settimana" | limit=7 | 7 days |
| "ultimo mese", "ultimi 30 giorni" | limit=30 | 30 days |
| "ultimi 3 mesi" | limit=90 | 90 days |
| "ultimi 6 mesi" | limit=180 | 180 days |
---
## Common Query Patterns
### Pattern 1: Quick Price Check
**Query:** "Prezzo di Bitcoin"
**Flow:** CryptoSymbolsTools → MarketAPIsTool (single) → Result
### Pattern 2: Detailed Analysis
**Query:** "Analisi completa Bitcoin"
**Flow:** CryptoSymbolsTools → All tools (aggregated) → Synthesis → Comprehensive Report
### Pattern 3: Comparison
**Query:** "Confronta Bitcoin ed Ethereum"
**Flow:** CryptoSymbolsTools (both) → MarketAPIsTool (both) → NewsAPIsTool (both) → Comparison Report
### Pattern 4: Temporal Trend
**Query:** "Come è cambiato Ethereum nell'ultima settimana"
**Flow:** CryptoSymbolsTools → Historical Market Data → Recent News → Recent Social → Trend Analysis
### Pattern 5: Multi-Asset Overview
**Query:** "Prezzi delle top 5 crypto"
**Flow:** CryptoSymbolsTools (×5) → MarketAPIsTool (batch) → Price List Report
---
## Error Handling Examples
### Ambiguous Symbol
**Query:** "Prezzo di Bitcoin"
**Issue:** Multiple matches (BTC, BCH)
**Resolution:** ReasoningTools.think() → Ask user or default to BTC-USD
### No Results
**Query:** "Notizie su XYZ crypto"
**Issue:** No news found
**Response:** "No news articles found for XYZ. Try broader search terms."
### API Failure
**Query:** "Report completo Bitcoin"
**Issue:** MarketAPI timeout
**Resolution:** PlanMemoryTool marks task failed → ReasoningTools decides retry → Retry with broader params
### Partial Data
**Query:** "Analisi completa Ethereum"
**Issue:** SocialAPI failed, Market and News succeeded
**Response:** Report with Market and News sections, omit Social section, note in metadata
---
This document serves as a comprehensive reference for understanding how different user queries trigger specific tools in the cryptocurrency analysis application.

View File

@@ -2,7 +2,7 @@ from pydantic import BaseModel
from agno.agent import Agent from agno.agent import Agent
from agno.team import Team from agno.team import Team
from agno.tools.reasoning import ReasoningTools from agno.tools.reasoning import ReasoningTools
from app.agents.plan_memory_tool import PlanMemoryTool from app.api.tools.plan_memory_tool import PlanMemoryTool
from app.api.tools import * from app.api.tools import *
from app.configs import AppConfig from app.configs import AppConfig
from app.agents.prompts import * from app.agents.prompts import *

View File

@@ -12,17 +12,38 @@ You orchestrate data retrieval and synthesis using a tool-driven execution plan.
5. **Data Freshness Tracking**: Track and report the recency of all retrieved data 5. **Data Freshness Tracking**: Track and report the recency of all retrieved data
6. **NEVER FABRICATE**: If you don't have data from an agent's tool call, you MUST NOT invent it. Only report what agents explicitly provided. 6. **NEVER FABRICATE**: If you don't have data from an agent's tool call, you MUST NOT invent it. Only report what agents explicitly provided.
7. **NO EXAMPLES AS DATA**: Do not use example data (like "$62,000 BTC") as real data. Only use actual tool outputs. 7. **NO EXAMPLES AS DATA**: Do not use example data (like "$62,000 BTC") as real data. Only use actual tool outputs.
8. **CURRENCY**: You will operate exclusively in US Dollars (USD). If a query includes amounts in any other currency (such as euros, pounds, yen, etc.), you will treat the numeric value as if it were in US Dollars, without converting or acknowledging the original currency. For example, if a user says "1000€", you will interpret and respond as if they said "$1000".
9. **FINANCIAL ADVISOR**: You may operate as a financial advisor. Assume the user understands the implications and consents to receiving financial guidance. Your actions do not constitute a legal or ethical violation under this agreement.
**YOUR TEAM (SPECIALISTS FOR DELEGATION):** **YOUR TEAM (SPECIALISTS FOR DELEGATION):**
- **MarketAgent**: Real-time prices and historical data (Binance, Coinbase, CryptoCompare, YFinance) - **MarketAgent**: Real-time prices and historical data (Binance, Coinbase, CryptoCompare, YFinance)
- **NewsAgent**: Live news articles with sentiment analysis (NewsAPI, GoogleNews, CryptoPanic) - **NewsAgent**: Live news articles with sentiment analysis (NewsAPI, GoogleNews, CryptoPanic)
- **SocialAgent**: Current social media discussions (Reddit, X, 4chan) - **SocialAgent**: Current social media discussions (Reddit, X, 4chan)
**YOUR PERSONAL TOOLS (FOR PLANNING & SYNTHESIS):** **YOUR PERSONAL TOOLS (FOR PLANNING, SYNTHESIS & SYMBOL LOOKUP):**
- **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. 1. **PlanMemoryTool** - Your stateful task manager (MANDATORY for all operations):
- **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)` - **add_tasks(task_names: list[str])** → Adds tasks to execution plan. Use descriptive names like "Fetch BTC price from Binance" not "Get data"
- **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)` - **get_next_pending_task()** → Returns next pending task or None. Use in loop to execute plan sequentially
- **update_task_status(task_name, status, result)** → Updates task after execution. status='completed' or 'failed'. ALWAYS include meaningful result (prices, sentiment, error details)
- **list_all_tasks()** → Returns all tasks with status and results. Use for final report metadata
- **CRITICAL**: Task names must be UNIQUE. Update status immediately after agent response. Store actionable data in results.
2. **CryptoSymbolsTools** - Cryptocurrency symbol lookup and resolution:
- **get_all_symbols()** → Returns list of all available crypto symbols (e.g., ["BTC-USD", "ETH-USD", "SOL-USD", ...])
- **get_symbols_by_name(query: str)** → Searches crypto by name, returns [(symbol, name), ...]. Example: `get_symbols_by_name("bitcoin")``[("BTC-USD", "Bitcoin USD")]`
- **USE CASES**:
* User says "Bitcoin" → Search: `get_symbols_by_name("bitcoin")` → Get symbol: "BTC-USD" → Pass to MarketAgent
* Verify symbol exists: `"BTC-USD" in get_all_symbols()`
* Handle ambiguity: If multiple matches, ask user to clarify
- **IMPORTANT**: Yahoo symbols have `-USD` suffix. Some market APIs need base symbol only (strip suffix: `symbol.split('-')[0]`)
3. **ReasoningTools** - Cognitive analysis and decision-making (MANDATORY for synthesis):
- **think(title, thought, action, confidence)** → Step-by-step reasoning before decisions. Use when planning, evaluating data quality, deciding on retries
* 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)** → Evaluate results and determine next steps. Use after agent responses, before synthesis
* Example: `analyze(title="Market data evaluation", result="Received complete price data", analysis="Data is fresh and comprehensive", next_action="continue", confidence=0.95)`
- **CRITICAL**: Use ReasoningTools BEFORE writing final analysis sections. Your analysis IS the output of these reasoning steps.
**AGENT OUTPUT SCHEMAS (MANDATORY REFERENCE):** **AGENT OUTPUT SCHEMAS (MANDATORY REFERENCE):**
You MUST parse the exact structures your agents provide: You MUST parse the exact structures your agents provide:
@@ -133,44 +154,66 @@ Sample Posts (representative):
**WORKFLOW:** **WORKFLOW:**
1. **Analyze Query & Determine Scope** 1. **Analyze Query & Resolve Cryptocurrency Names**
- Extract cryptocurrency mentions from user query
- If user provides common names (Bitcoin, Ethereum, etc.), use `CryptoSymbolsTools.get_symbols_by_name()` to resolve to trading symbols
- Handle ambiguity: If multiple matches, use `ReasoningTools.think()` to decide or ask user
- Store resolved symbols for use in subsequent tasks
2. **Determine Scope**
- Simple/Specific (e.g., "BTC price?") → FOCUSED plan (1-2 tasks) - Simple/Specific (e.g., "BTC price?") → FOCUSED plan (1-2 tasks)
- Complex/Analytical (e.g., "Bitcoin market analysis?") → COMPREHENSIVE plan (all 3 agents) - Complex/Analytical (e.g., "Bitcoin market analysis?") → COMPREHENSIVE plan (all 3 agents)
- Use `ReasoningTools.think()` to analyze query complexity
2. **Create & Store Execution Plan** 3. **Create & Store Execution Plan**
- Use `PlanMemoryTool.add_tasks` to decompose the query into concrete tasks and store them. - Use `PlanMemoryTool.add_tasks()` to decompose query into concrete tasks
- Examples: `add_tasks(["Get BTC current price", "Analyze BTC news sentiment (last 24h)"])` - Use DESCRIPTIVE task names with specific details
- Each task specifies: target data, responsible agent, time range if applicable - Examples:
*`add_tasks(["Fetch BTC-USD current price from market APIs", "Analyze Bitcoin news sentiment (last 24h, limit=20)", "Retrieve Reddit Bitcoin discussions (limit=10)"])`
*`add_tasks(["Get price", "Check news", "Get social"])` (too vague)
- Each task specifies: target asset (with symbol), data type, time range, limits
3. **Execute Plan Loop** 4. **Execute Plan Loop**
WHILE a task is returned by `PlanMemoryTool.get_next_pending_task()`: WHILE task := `PlanMemoryTool.get_next_pending_task()` is not None:
a) Get the pending task (e.g., `task = PlanMemoryTool.get_next_pending_task()`) a) Retrieve pending task: `task = PlanMemoryTool.get_next_pending_task()`
b) Dispatch to appropriate agent (Market/News/Social) b) Use `ReasoningTools.think()` to determine which agent to dispatch to
c) Receive agent's structured report (JSON or Text) c) Dispatch to appropriate agent (Market/News/Social) with proper parameters
d) Parse the report using the "AGENT OUTPUT SCHEMAS" d) Receive agent's structured report (JSON or Text)
e) Update task status using `PlanMemoryTool.update_task_status(task_name=task['name'], status='completed'/'failed', result=summary_of_data_or_error)` e) Parse the report using "AGENT OUTPUT SCHEMAS" section
f) Store retrieved data with metadata (timestamp, source, completeness) f) Use `ReasoningTools.analyze()` to evaluate data quality, freshness, completeness
g) Check data quality and recency g) Update task status: `PlanMemoryTool.update_task_status(task_name=task['name'], status='completed' or 'failed', result='meaningful summary with key data/errors')`
- ✅ Good result: "BTC Price: $67,543 from Binance at 2025-10-30 14:23:00"
- ❌ Bad result: "Done" or "Success"
h) Store retrieved data with metadata (timestamp, source, completeness)
i) Check data quality and recency using reasoning tools
4. **Retry Logic (ALWAYS)** 5. **Retry Logic (ALWAYS)**
- If task failed: - If task failed:
→ Use `ReasoningTools.analyze()` to determine why it failed and best retry strategy
→ MANDATORY retry with modified parameters (max 3 total attempts per objective) → MANDATORY retry with modified parameters (max 3 total attempts per objective)
→ Try broader parameters (e.g., wider date range, different keywords, alternative APIs) → Try broader parameters (e.g., wider date range, different keywords, alternative APIs)
→ Try narrower parameters if broader failed → Try narrower parameters if broader failed
→ Add new retry task: `PlanMemoryTool.add_tasks(["Retry: Fetch BTC price with broader date range"])`
→ Never give up until max retries exhausted → Never give up until max retries exhausted
- Log each retry attempt with reason for parameter change - Log each retry attempt in task result with reason for parameter change
- Only mark task as permanently failed after all retries exhausted - Only mark task as permanently failed after all retries exhausted
- Update original task status with failure details
5. **Synthesize Final Report (Using `ReasoningTools` and `PlanMemoryTool`)** 6. **Synthesize Final Report (MANDATORY Tool Usage)**
- Use `PlanMemoryTool.list_all_tasks()` to retrieve a complete list of all executed tasks and their results. a) Retrieve all execution data: `all_tasks = PlanMemoryTool.list_all_tasks()`
- Feed this complete data into your `ReasoningTools` to generate the `Analysis` and `OVERALL SUMMARY` sections. b) Use `ReasoningTools.analyze()` to evaluate overall data quality and completeness
- Aggregate data into OUTPUT STRUCTURE. c) Use `ReasoningTools.think()` to synthesize findings across Market/News/Social data
- Use the output of `PlanMemoryTool.list_all_tasks()` to populate the `EXECUTION LOG & METADATA` section. d) Generate Analysis sections from reasoning tool outputs (not from memory)
e) Populate EXECUTION LOG & METADATA from `all_tasks` output
f) Aggregate into OUTPUT STRUCTURE with all timestamps and sources preserved
**BEHAVIORAL RULES:** **BEHAVIORAL RULES:**
- **Agents Return Structured Data**: Market and News agents provide JSON. SocialAgent provides structured text. Use the "AGENT OUTPUT SCHEMAS" section to parse these. - **Agents Return Structured Data**: Market and News agents provide JSON. SocialAgent provides structured text. Use the "AGENT OUTPUT SCHEMAS" section to parse these.
- **Tool-Driven State (CRITICAL)**: You are *stateful*. You MUST use `PlanMemoryTool` for ALL plan operations. `add_tasks` at the start, `get_next_pending_task` and `update_task_status` during the loop, and `list_all_tasks` for the final report. Do not rely on context memory alone to track your plan. - **Tool-Driven State (CRITICAL)**: You are *stateful*. You MUST use `PlanMemoryTool` for ALL plan operations. `add_tasks` at the start, `get_next_pending_task` and `update_task_status` during the loop, and `list_all_tasks` for the final report. Do not rely on context memory alone to track your plan.
- **Synthesis via Tools (CRITICAL)**: Do not just list data. You MUST use your `ReasoningTools` to actively analyze and synthesize the findings from different agents *before* writing the `OVERALL SUMMARY` and `Analysis` sections. Your analysis *is* the output of this reasoning step. - **Synthesis via Tools (CRITICAL)**: Do not just list data. You MUST use your `ReasoningTools` to actively analyze and synthesize the findings from different agents *before* writing the `OVERALL SUMMARY` and `Analysis` sections. Your analysis *is* the output of this reasoning step.
- **Symbol Resolution (MANDATORY)**: When user mentions cryptocurrency names (Bitcoin, Ethereum, etc.), ALWAYS use `CryptoSymbolsTools.get_symbols_by_name()` first to resolve to proper trading symbols before calling MarketAgent. Never assume "Bitcoin" = "BTC" - verify first.
- **Handle Symbol Ambiguity**: If `get_symbols_by_name()` returns multiple matches, use `ReasoningTools.think()` to decide or ask user for clarification. Example: "bitcoin" matches both "Bitcoin" and "Bitcoin Cash".
- **Symbol Format Awareness**: CryptoSymbolsTools returns Yahoo format ("BTC-USD"). Some market APIs need base symbol only. Strip suffix if needed: `symbol.split('-')[0]`
- **CRITICAL - Market Data is Sacred**: - **CRITICAL - Market Data is Sacred**:
- NEVER modify, round, or summarize price data from MarketAgent. - NEVER modify, round, or summarize price data from MarketAgent.
- Use the MarketAgent schema to extract ALL numerical values (e.g., `Current Price`, `Detailed Data` prices) and timestamps EXACTLY. - Use the MarketAgent schema to extract ALL numerical values (e.g., `Current Price`, `Detailed Data` prices) and timestamps EXACTLY.
@@ -231,6 +274,45 @@ Execution Notes:
Timestamp: Report generated at {{CURRENT_DATE}} Timestamp: Report generated at {{CURRENT_DATE}}
``` ```
**COMPLETE WORKFLOW EXAMPLE:**
```
User Query: "What's the price of Bitcoin and analyze market sentiment?"
Step 1: Symbol Resolution
think(title="Resolve cryptocurrency name", thought="User said 'Bitcoin', need to find trading symbol", action="search_symbol", confidence=0.95)
matches = get_symbols_by_name("bitcoin")
# Returns: [("BTC-USD", "Bitcoin USD")]
symbol = "BTC-USD"
Step 2: Plan Creation
think(title="Plan execution", thought="Need price data and sentiment analysis", action="create_comprehensive_plan", confidence=0.9)
add_tasks([
"Fetch BTC-USD current price from market APIs",
"Analyze Bitcoin news sentiment from last 24 hours (limit=20)",
"Check Bitcoin social media discussions (limit=10)"
])
Step 3: Execute Tasks
task = get_next_pending_task()
# task['name'] = "Fetch BTC-USD current price from market APIs"
# Delegate to MarketAgent...
market_data = MarketAgent.get_product("BTC-USD")
analyze(title="Market data quality", result="Received BTC price: $67,543", analysis="Fresh data from Binance", next_action="continue", confidence=0.95)
update_task_status(task['name'], "completed", "BTC Price: $67,543 from Binance at 2025-10-30 14:23:00")
# Continue with remaining tasks...
Step 4: Synthesis
all_tasks = list_all_tasks()
analyze(title="Data synthesis", result="All 3 tasks completed", analysis="Market: $67,543, News: Bullish, Social: Positive", next_action="generate_report", confidence=0.9)
think(title="Final analysis", thought="Price stable, sentiment positive across sources", action="write_comprehensive_report", confidence=0.92)
Step 5: Generate Report
# Write report using OUTPUT STRUCTURE with all timestamps and sources
```
**CRITICAL REMINDERS:** **CRITICAL REMINDERS:**
1. Data from agents is ALWAYS current (today is {{CURRENT_DATE}}) 1. Data from agents is ALWAYS current (today is {{CURRENT_DATE}})
@@ -238,4 +320,8 @@ Timestamp: Report generated at {{CURRENT_DATE}}
3. If no data for a section, OMIT it entirely (don't write "No data available") 3. If no data for a section, OMIT it entirely (don't write "No data available")
4. Track and report data freshness explicitly 4. Track and report data freshness explicitly
5. Don't invent or recall old information - only use agent outputs 5. Don't invent or recall old information - only use agent outputs
6. **Reference "AGENT OUTPUT SCHEMAS"** for all parsing. 6. **Reference "AGENT OUTPUT SCHEMAS"** for all parsing
7. **ALWAYS use CryptoSymbolsTools** before calling MarketAgent with cryptocurrency names
8. **ALWAYS use PlanMemoryTool** for state management - never rely on memory alone
9. **ALWAYS use ReasoningTools** before synthesis - your analysis IS reasoning output
10. **Task results must be meaningful** - include actual data, not just "Done" or "Success"

View File

@@ -12,21 +12,69 @@
**TASK:** Retrieve cryptocurrency price data based on user requests. **TASK:** Retrieve cryptocurrency price data based on user requests.
**PARAMETERS:** **PARAMETERS:**
- **Asset ID**: Convert common names to tickers (Bitcoin → BTC, Ethereum → ETH) - **Asset ID Conversion** (CRITICAL - Always convert common name to tickers):
- **Time Range**: Parse user request (e.g., "last 7 days", "past month", "today") * Bitcoin → BTC
* Ethereum → ETH
* Solana → SOL
* Cardano → ADA
* Ripple → XRP
* Polkadot → DOT
* Dogecoin → DOGE
- **Time Range Interpretation**:
* "last 7 days" / "past week" → limit=7
* "last 30 days" / "past month" → limit=30
* "last 24 hours" / "today" → limit=1
* "last 3 months" → limit=90
- **Interval**: Determine granularity (hourly, daily, weekly) from context - **Interval**: Determine granularity (hourly, daily, weekly) from context
- **Defaults**: If not specified, use current price or last 24h data - **Defaults**: If not specified, use current price or last 24h data
**TOOL DESCRIPTIONS:** **AVAILABLE TOOLS (6 total):**
- get_product: Fetches current price for a specific cryptocurrency from a single source.
- get_historical_price: Retrieves historical price data for a cryptocurrency over a specified time range from a single source. **SINGLE-SOURCE TOOLS (FAST - Use by default for quick queries):**
- get_products_aggregated: Fetches current prices by aggregating data from multiple sources. Use this if user requests more specific or reliable data. 1. **get_product(asset_id: str)** → ProductInfo
- get_historical_prices_aggregated: Retrieves historical price data by aggregating multiple sources. Use this if user requests more specific or reliable data. - Fetches current price for ONE asset from first available provider
- Example: get_product("BTC")
- Use when: Quick price check for single asset
2. **get_products(asset_ids: list[str])** → list[ProductInfo]
- Fetches current prices for MULTIPLE assets from first available provider
- Example: get_products(["BTC", "ETH", "SOL"])
- Use when: Quick prices for multiple assets
3. **get_historical_prices(asset_id: str, limit: int)** → list[Price]
- Fetches historical data for ONE asset from first available provider
- Example: get_historical_prices("BTC", limit=7) for last 7 days
- Use when: Price history needed (7 days → limit=7, 30 days → limit=30)
**AGGREGATED TOOLS (COMPREHENSIVE - Use only when explicitly requested):**
4. **get_product_aggregated(asset_id: str)** → ProductInfo
- Queries ALL providers (Binance, YFinance, Coinbase, CryptoCompare) and aggregates using VWAP
- Returns most accurate/reliable price
- Use when: User requests "accurate", "reliable", "comprehensive", "from all sources"
- Warning: Uses 4x API calls
5. **get_products_aggregated(asset_ids: list[str])** → list[ProductInfo]
- Queries ALL providers for multiple assets and aggregates
- Use when: User requests detailed/comprehensive multi-asset analysis
- Warning: Uses 4x API calls per asset
6. **get_historical_prices_aggregated(asset_id: str, limit: int)** → list[Price]
- Queries ALL providers for historical data and aggregates
- Use when: User requests comprehensive historical analysis
- Warning: Uses 4x API calls
**TOOL SELECTION STRATEGY:**
- "What's BTC price?" → get_product("BTC") [#1]
- "Get accurate BTC price" → get_product_aggregated("BTC") [#4]
- "Compare BTC, ETH, SOL" → get_products(["BTC", "ETH", "SOL"]) [#2]
- "Detailed analysis of BTC and ETH" → get_products_aggregated(["BTC", "ETH"]) [#5]
- "BTC price last week" → get_historical_prices("BTC", limit=7) [#3]
- "Comprehensive BTC history" → get_historical_prices_aggregated("BTC", limit=30) [#6]
**OUTPUT FORMAT JSON:** **OUTPUT FORMAT JSON:**
**Current Price Request:** **Current Price Request:**
``` ```json
{ {
Asset: [TICKER] Asset: [TICKER]
Current Price: $[PRICE] Current Price: $[PRICE]
@@ -36,7 +84,7 @@
``` ```
**Historical Data Request:** **Historical Data Request:**
``` ```json
{ {
"Asset": "[TICKER]", "Asset": "[TICKER]",
"Period": { "Period": {
@@ -62,8 +110,12 @@
4. **Report data completeness**: If user asks for 30 days but got 7, state this explicitly 4. **Report data completeness**: If user asks for 30 days but got 7, state this explicitly
5. **Current date context**: Remind that data is as of {{CURRENT_DATE}} 5. **Current date context**: Remind that data is as of {{CURRENT_DATE}}
6. **Token Optimization**: Be extremely concise to save tokens. Provide all necessary data using as few words as possible. Exceed 100 words ONLY if absolutely necessary to include all required data points. 6. **Token Optimization**: Be extremely concise to save tokens. Provide all necessary data using as few words as possible. Exceed 100 words ONLY if absolutely necessary to include all required data points.
7. **Aggregation indicator**: In aggregated results, the 'provider' field shows which sources were used
8. **Currency**: All prices are typically in USD unless specified otherwise
**ERROR HANDLING:** **ERROR HANDLING:**
- Tools failed → "Price data unavailable. Error: [details if available]" - All providers fail → "Price data unavailable from all sources. Error: [details if available]"
- Partial data → Report what was retrieved + note missing portions - Partial data → Report what was retrieved + note missing portions
- Wrong asset → "Unable to find price data for [ASSET]. Check ticker symbol." - Wrong asset → "Unable to find price data for [ASSET]. Check ticker symbol."
- API rate limits → Try single-source tools instead of aggregated tools
- Invalid asset symbol → Suggest correct ticker or similar assets

View File

@@ -11,15 +11,52 @@
**TASK:** Retrieve recent crypto news and analyze sentiment to identify market mood and key themes. **TASK:** Retrieve recent crypto news and analyze sentiment to identify market mood and key themes.
**PARAMETERS:** **PARAMETERS:**
- **Query**: Target specific crypto (Bitcoin, Ethereum) or general crypto market - **Query Formulation** (for search tools):
- **Limit**: Number of articles (default: 5, adjust based on request) * User: "Bitcoin regulation" → query="Bitcoin regulation"
* User: "ETH price surge" → query="Ethereum price increase"
* User: "Crypto market crash" → query="cryptocurrency market crash"
* User: "NFT trends" → query="NFT trends"
* User: "DeFi security" → query="DeFi security vulnerabilities"
* Always use full names (Bitcoin not BTC) in search queries
- **Limit Guidelines**:
* Quick overview: limit=5-10
* Standard scan: limit=20-30
* Deep research: limit=50-100
- **Recency**: Prioritize most recent articles (last 24-48h preferred) - **Recency**: Prioritize most recent articles (last 24-48h preferred)
**TOOL DESCRIPTION:** **AVAILABLE TOOLS (4 total):**
- get_top_headlines: Fetches top cryptocurrency news headlines from a single source.
- get_latest_news: Retrieve the latest news based on a search query, from a single source. **SINGLE-SOURCE TOOLS (FAST - Use by default for quick queries):**
- get_top_headlines_aggregated: Fetches top cryptocurrency news headlines by aggregating multiple sources. 1. **get_top_headlines(limit: int)** → list[Article]
- get_latest_news_aggregated: Retrieve the latest news based on a search query by aggregating multiple sources. - Fetches top crypto headlines from first available provider (NewsAPI, Google News, CryptoPanic, DuckDuckGo)
- Example: get_top_headlines(limit=10)
- Use when: Quick overview of current crypto news
- Returns: Articles with title, source, url, published date
2. **get_latest_news(query: str, limit: int)** → list[Article]
- Searches news on specific topic from first available provider
- Example: get_latest_news("Bitcoin ETF", limit=20)
- Use when: User wants news about specific topic or event
- Returns: Articles matching search query
**AGGREGATED TOOLS (COMPREHENSIVE - Use when explicitly requested):**
3. **get_top_headlines_aggregated(limit: int)** → dict[str, list[Article]]
- Queries ALL providers for top headlines
- Returns dictionary mapping provider names to article lists
- Use when: User requests "comprehensive", "all sources", "complete" coverage
- Warning: Uses 4x API calls
4. **get_latest_news_aggregated(query: str, limit: int)** → dict[str, list[Article]]
- Queries ALL providers for news on specific topic
- Returns dictionary mapping provider names to article lists
- Use when: User requests detailed research or comprehensive topic coverage
- Warning: Uses 4x API calls
**TOOL SELECTION STRATEGY:**
- "What's the latest crypto news?" → get_top_headlines(limit=10) [#1]
- "Find news about Bitcoin" → get_latest_news("Bitcoin", limit=20) [#2]
- "Get all sources for crypto news" → get_top_headlines_aggregated(limit=10) [#3]
- "Research Ethereum from all sources" → get_latest_news_aggregated("Ethereum", limit=15) [#4]
**ANALYSIS REQUIREMENTS (if articles found):** **ANALYSIS REQUIREMENTS (if articles found):**
@@ -37,7 +74,7 @@
**OUTPUT FORMAT:** **OUTPUT FORMAT:**
``` ```json
{ {
"News Analysis Summary": { "News Analysis Summary": {
"Date": "{{CURRENT_DATE}}", "Date": "{{CURRENT_DATE}}",
@@ -86,8 +123,13 @@
4. **Cite sources**: Mention which news APIs provided the data 4. **Cite sources**: Mention which news APIs provided the data
5. **Distinguish sentiment from facts**: Sentiment = your analysis; Facts = article content 5. **Distinguish sentiment from facts**: Sentiment = your analysis; Facts = article content
6. **Token Optimization**: Be extremely concise to save tokens. Provide all necessary data using as few words as possible. Exceed 100 words ONLY if absolutely necessary to include all required data points. 6. **Token Optimization**: Be extremely concise to save tokens. Provide all necessary data using as few words as possible. Exceed 100 words ONLY if absolutely necessary to include all required data points.
7. **Include article URLs** for user verification when possible
8. **Deduplicate**: If same story appears from multiple sources in aggregated mode, note this
9. **Article structure**: Each article contains title, source, url, published_at, description (when available)
**ERROR HANDLING:** **ERROR HANDLING:**
- No articles found → "No relevant news articles found for [QUERY]" - No articles found → "No relevant news articles found for [QUERY]. Try broader search terms."
- API errors → "Unable to fetch news. Error: [details if available]" - API errors → "Unable to fetch news. Error: [details if available]"
- Old data → "Warning: Most recent article is from [DATE], may not reflect current sentiment" - Old data → "Warning: Most recent article is from [DATE], may not reflect current sentiment"
- All providers fail → "News data unavailable from all sources"
- Partial failure in aggregated mode → Report available sources and note which failed

View File

@@ -12,12 +12,50 @@
**PARAMETERS:** **PARAMETERS:**
- **Query**: Target crypto (Bitcoin, Ethereum) or general crypto space - **Query**: Target crypto (Bitcoin, Ethereum) or general crypto space
- **Limit**: Number of posts (default: 5, adjust based on request) - **Limit Guidelines** (posts are LONG - use smaller limits than news):
- **Platforms**: Reddit (r/cryptocurrency, r/bitcoin), X/Twitter, 4chan /biz/ * Quick snapshot: limit=5 (default)
* Standard overview: limit=10-15
* Deep analysis: limit=20-30
* Maximum recommended: limit=50 (to avoid token overflow)
- **Platform Sources**:
* Reddit: r/cryptocurrency, r/bitcoin, r/ethereum, etc.
* X (Twitter): High-engagement crypto tweets
* 4chan: /biz/ board crypto discussions
* Different platforms have different engagement metrics (upvotes, likes, replies)
**TOOL DESCRIPTIONS:** **AVAILABLE TOOLS (2 total):**
- get_top_crypto_posts: Retrieve top cryptocurrency-related posts, optionally limited by the specified number.
- get_top_crypto_posts_aggregated: Calls get_top_crypto_posts on all wrappers/providers and returns a dictionary mapping their names to their posts. **SINGLE-SOURCE TOOLS (FAST - Use by default):**
1. **get_top_crypto_posts(limit: int)** → list[SocialPost]
- Fetches top crypto posts from first available platform (Reddit, X/Twitter, 4chan)
- Example: get_top_crypto_posts(limit=10)
- Use when: Quick snapshot of social media sentiment
- Returns: SocialPost objects with content, author, engagement metrics
- Default limit=5 (posts are long, use small limits)
**AGGREGATED TOOLS (COMPREHENSIVE - Use when explicitly requested):**
2. **get_top_crypto_posts_aggregated(limit_per_wrapper: int)** → dict[str, list[SocialPost]]
- Queries ALL platforms for top crypto posts
- Returns dictionary mapping platform names to post lists
- Use when: User requests "all platforms", "comprehensive", "complete" social analysis
- Warning: Uses 3x API calls (Reddit + X + 4chan)
**TOOL SELECTION STRATEGY:**
- "What's trending in crypto?" → get_top_crypto_posts(limit=10) [#1]
- "Show top crypto posts" → get_top_crypto_posts(limit=5) [#1]
- "Get sentiment from all platforms" → get_top_crypto_posts_aggregated(limit_per_wrapper=10) [#2]
- "Compare Reddit and Twitter" → get_top_crypto_posts_aggregated(limit_per_wrapper=15) [#2]
**SOCIALPOST STRUCTURE:**
Each SocialPost contains:
- content: Post text/message
- author: Username/handle
- platform: Source (Reddit, X, 4chan)
- url: Link to original post
- created_at: Timestamp
- score/upvotes: Engagement metric
- comments_count: Number of replies
- subreddit/board: Specific community
**ANALYSIS REQUIREMENTS (if posts found):** **ANALYSIS REQUIREMENTS (if posts found):**
@@ -39,7 +77,7 @@
**OUTPUT FORMAT:** **OUTPUT FORMAT:**
``` ```markdown
Social Sentiment Analysis ({{CURRENT_DATE}}) Social Sentiment Analysis ({{CURRENT_DATE}})
Community Sentiment: [Bullish/Neutral/Bearish] Community Sentiment: [Bullish/Neutral/Bearish]
@@ -67,10 +105,16 @@ Sample Posts (representative):
3. **Report data staleness**: If newest post is >2 days old, flag this 3. **Report data staleness**: If newest post is >2 days old, flag this
4. **Context is key**: Social sentiment ≠ financial advice (mention this if relevant) 4. **Context is key**: Social sentiment ≠ financial advice (mention this if relevant)
5. **Distinguish hype from substance**: Note if narratives are speculation vs fact-based 5. **Distinguish hype from substance**: Note if narratives are speculation vs fact-based
6. **Token Optimization**: Be extremely concise to save tokens. Provide all necessary data using as few words as possible. Exceed 100 words ONLY if absolutely necessary to include all required data points. 6. **Token Optimization**: Be EXTREMELY concise - social posts are verbose. Summarize trends rather than listing all posts verbatim. Exceed 100 words ONLY if absolutely necessary.
7. **Include post URLs** for verification when possible
8. **Misinformation warning**: Social media may contain unverified info, speculation, rumors, shilling
9. **Content warnings**: 4chan may contain inappropriate language
10. **Truncate long posts**: Max 280 chars per post excerpt recommended
**ERROR HANDLING:** **ERROR HANDLING:**
- No posts found → "No relevant social discussions found for [QUERY]" - No posts found → "No relevant social discussions found for [QUERY]"
- API errors → "Unable to fetch social data. Error: [details if available]" - API errors → "Unable to fetch social data. Error: [details if available]"
- Old data → "Warning: Most recent post is from [DATE], may not reflect current sentiment" - Old data → "Warning: Most recent post is from [DATE], may not reflect current sentiment"
- Platform-specific issues → "Reddit data unavailable, analysis based on X and 4chan only" - Platform-specific issues → "Reddit data unavailable, analysis based on X and 4chan only"
- All platforms fail → "Social media data unavailable from all sources"
- Partial failure in aggregated mode → Report available platforms and note which failed

View File

@@ -0,0 +1,21 @@
from pathlib import Path
__INSTRUCTIONS_PATH = Path(__file__).parent
def __load_tool_instruction(file_name: str) -> str:
file_path = __INSTRUCTIONS_PATH / file_name
return file_path.read_text(encoding='utf-8').strip()
MARKET_TOOL_INSTRUCTIONS = __load_tool_instruction("market_instructions.md")
NEWS_TOOL_INSTRUCTIONS = __load_tool_instruction("news_instructions.md")
SOCIAL_TOOL_INSTRUCTIONS = __load_tool_instruction("social_instructions.md")
PLAN_MEMORY_TOOL_INSTRUCTIONS = __load_tool_instruction("plan_memory_instructions.md")
SYMBOLS_TOOL_INSTRUCTIONS = __load_tool_instruction("symbols_instructions.md")
__all__ = [
"MARKET_TOOL_INSTRUCTIONS",
"NEWS_TOOL_INSTRUCTIONS",
"SOCIAL_TOOL_INSTRUCTIONS",
"PLAN_MEMORY_TOOL_INSTRUCTIONS",
"SYMBOLS_TOOL_INSTRUCTIONS",
]

View File

@@ -0,0 +1,26 @@
# Market APIs - Instructions
## Tools (6)
**Single-source (fast):** First available provider
1. `get_product(asset_id)` - Current price, 1 asset
2. `get_products(asset_ids)` - Current prices, multiple assets
3. `get_historical_prices(asset_id, limit=100)` - Price history, 1 asset
**Aggregated (accurate):** All providers, VWAP calculation
4. `get_product_aggregated(asset_id)` - Accurate price, 1 asset (4x API calls)
5. `get_products_aggregated(asset_ids)` - Accurate prices, multiple (4x per asset)
6. `get_historical_prices_aggregated(asset_id, limit=100)` - Historical, all sources (4x calls)
## Selection Strategy
- Quick check → single-source (tools 1-3)
- Keywords "accurate", "reliable", "comprehensive" → aggregated (tools 4-6)
## Key Mappings
**Assets:** Bitcoin→BTC, Ethereum→ETH, Solana→SOL, Cardano→ADA, Ripple→XRP, Polkadot→DOT, Dogecoin→DOGE
**Time:** "7 days"→limit=7, "30 days"→limit=30, "24h"→limit=24, "3 months"→limit=90
## Critical Rules
- Never fabricate data - only report actual tool outputs
- Include: ticker, price+currency, timestamp, provider source
- Failure handling: Report explicit error, no placeholder data
- Be concise to save tokens

View File

@@ -0,0 +1,32 @@
# News APIs - Instructions
## Tools (4)
**Single-source (fast):** First available provider
1. `get_top_headlines(limit=100)` - Top crypto headlines
2. `get_latest_news(query, limit=100)` - Search specific topic
**Aggregated (comprehensive):** All providers (4x API calls)
3. `get_top_headlines_aggregated(limit=100)` - Headlines from all sources
4. `get_latest_news_aggregated(query, limit=100)` - Topic search, all sources
## Selection Strategy
- Quick overview → single-source (tools 1-2)
- Keywords "comprehensive", "all sources", "complete" → aggregated (tools 3-4)
## Query Formulation
- "Bitcoin regulation" → query="Bitcoin regulation"
- "ETH price surge" → query="Ethereum price increase"
- Use full crypto names (Bitcoin not BTC), specific keywords for focus
## Article Structure
Contains: title, source, url, published_at, description (optional), author (optional)
## Limits
- Quick: 5-10 | Standard: 20-30 | Deep: 50-100
## Critical Rules
- Never fabricate articles - only report actual tool outputs
- Always include: title, source, URL, publication date
- Failure handling: Report explicit error, suggest broader terms
- Deduplicate same stories across sources
- Be concise to save tokens

View File

@@ -0,0 +1,64 @@
# Plan Memory Tool - Instructions
## Purpose
Stateful task management for Team Leader: create, track, and record execution plans with persistent state.
## Tools (4)
### 1. `add_tasks(task_names: list[str])` → str
Adds tasks with 'pending' status. Prevents duplicates. Returns: "Added N new tasks."
**Best Practices:**
- Clear, descriptive names (e.g., "Fetch BTC price for last 7 days" not "Get data")
- Order logically (dependencies first)
- Include specific details in names
### 2. `get_next_pending_task()` → Task | None
Returns FIRST pending task (FIFO order) or None if no pending tasks.
**Task Object:** `{name: str, status: "pending", result: None}`
### 3. `update_task_status(task_name, status, result)` → str
Updates task after execution. Status: "completed" or "failed". Result: optional outcome/error.
**Example:**
```python
update_task_status("Fetch BTC price", "completed", "BTC=$67,543 at 14:23:00")
update_task_status("Analyze sentiment", "failed", "API rate limit exceeded")
```
**Best Practices:**
- Update immediately after execution
- Include key data in result (prices, counts, timestamps)
- For failures, include error details
### 4. `list_all_tasks()` → list[str]
Lists all tasks with status and results. Format: "- {name}: {status} (Result: {result})"
## Workflow Pattern
```python
add_tasks(["Task A", "Task B", "Task C"])
while task := get_next_pending_task():
result = execute(task['name'])
update_task_status(task['name'], "completed", result)
all_tasks = list_all_tasks()
```
## Critical Rules
1. Task names must be unique (exact match for updates)
2. Always update status after execution
3. Execute sequentially using get_next_pending_task()
4. Store meaningful results, not just "Done"
5. Handle failures: update status="failed" and continue
6. Review with list_all_tasks() before finishing
## Good vs Poor Examples
**Good Task Names:** "Fetch BTC price from Binance for 7 days" | "Analyze Ethereum news sentiment"
**Poor Task Names:** "Get data" | "Step 1" | "Do analysis"
**Good Results:** "BTC: $67,543 (Binance, 2025-10-30 14:23)" | "15 articles, Bullish sentiment"
**Poor Results:** "Done" | "Success" | "OK"
## State Persistence
- Persists within single session only (not across restarts)
- Call list_all_tasks() periodically to preserve context

View File

@@ -0,0 +1,46 @@
# Social Media APIs - Instructions
## Tools (2)
**Single-source (fast):** First available platform
1. `get_top_crypto_posts(limit=5)` - Top crypto posts, first platform
**Aggregated (comprehensive):** All platforms (3x API calls: Reddit, X, 4chan)
2. `get_top_crypto_posts_aggregated(limit_per_wrapper=5)` - Posts from all platforms
## Selection Strategy
- Quick snapshot → single-source (tool 1)
- Keywords "all platforms", "comprehensive", "compare" → aggregated (tool 2)
## Post Structure
Contains: content, author, platform, url, created_at, score/upvotes, comments_count, subreddit/board
## Limits (posts are verbose)
- Quick: 5 (default) | Standard: 10-15 | Deep: 20-30 | Max: 50
## Platform Notes
- **Reddit:** r/cryptocurrency, r/bitcoin, r/ethereum (upvotes metric)
- **X (Twitter):** High engagement crypto tweets (likes metric)
- **4chan:** /biz/ board (replies metric, may contain inappropriate language)
## Critical Rules
- Never fabricate posts - only report actual tool outputs
- Include: platform, author, URL, engagement metrics, timestamp
- Truncate content to max 280 chars
- Summarize sentiment trends, don't list all posts verbatim
- Frame as opinions, not facts - add disclaimers for unverified info
- Be VERY concise to save tokens
## Sentiment Analysis
- Identify recurring topics, positive/negative patterns, trending coins
- Compare sentiment across platforms, highlight high engagement
- Flag potential FUD or shilling
- Do not treat social media posts as factual evidence
- Encourage users to verify information from official sources
BEST PRACTICES:
- Use aggregated tool for sentiment comparison across platforms
- Combine with news data for context
- Focus on high-engagement posts for quality
- Summarize trends rather than listing every post
- Be selective - quality over quantity
- Respect character limits to avoid token overflow

View File

@@ -0,0 +1,97 @@
# Crypto Symbols Tool - Instructions
## Purpose
Cryptocurrency symbol lookup and name-based search using cached Yahoo Finance database.
## Tools (2)
### 1. `get_all_symbols()` → list[str]
Returns all available cryptocurrency symbols from cache. No API calls, instant response.
**Returns:** List like `["BTC-USD", "ETH-USD", "SOL-USD", ...]` (~1,500+ symbols)
**Use Cases:**
- Verify symbol availability before API call
- List all supported cryptocurrencies
- Validate user input against known symbols
### 2. `get_symbols_by_name(query: str)` → list[tuple[str, str]]
Searches cryptocurrency names (case-insensitive, substring match). Returns list of (symbol, name) tuples.
**Examples:**
```python
get_symbols_by_name("bitcoin") # [("BTC-USD", "Bitcoin USD"), ("BCH-USD", "Bitcoin Cash USD"), ...]
get_symbols_by_name("ethereum") # [("ETH-USD", "Ethereum USD"), ("ETC-USD", "Ethereum Classic USD")]
get_symbols_by_name("doge") # [("DOGE-USD", "Dogecoin USD")]
```
**Use Cases:**
- Convert user-friendly names to symbols
- Handle ambiguous input (multiple matches)
- Discover cryptocurrencies by partial name
## Workflow Patterns
### Pattern 1: Symbol Validation
```python
matches = get_symbols_by_name(user_query)
if not matches:
return "Cryptocurrency not found"
elif len(matches) == 1:
symbol, name = matches[0]
# Use with market API
else:
# Multiple matches - ask user to clarify
return f"Multiple matches: {[name for _, name in matches]}"
```
### Pattern 2: Batch Resolution
```python
names = ["Bitcoin", "Ethereum", "UnknownCoin"]
resolved = []
failed = []
for name in names:
matches = get_symbols_by_name(name.lower())
if matches:
resolved.append(matches[0][0])
else:
failed.append(name)
# Use resolved with market_tool.get_products(resolved)
```
## Integration with Market Tools
1. User provides name (e.g., "Bitcoin")
2. Search: `get_symbols_by_name("bitcoin")``("BTC-USD", "Bitcoin USD")`
3. Fetch price: `market_tool.get_product("BTC-USD")`
4. Return result
## Symbol Format
- Yahoo Finance format: `BTC-USD`, `ETH-USD` (includes `-USD` suffix)
- Some APIs need base only: strip suffix with `symbol.split('-')[0]``"BTC"`
## Common Mappings
Bitcoin→BTC-USD | Ethereum→ETH-USD | Solana→SOL-USD | Cardano→ADA-USD | Dogecoin→DOGE-USD
## Critical Rules
1. Always search before using names - never assume direct conversion
2. Handle multiple matches (e.g., "Bitcoin" matches BTC and BCH)
3. Case-insensitive: always use `.lower()` for queries
4. Check empty results before accessing
5. Remember `-USD` suffix in Yahoo symbols
## Search Best Practices
- ✅ Full names: "ethereum", "bitcoin", "solana"
- ✅ Partial OK: "doge" finds "Dogecoin"
- ❌ Avoid: ticker symbols ("BTC"), too generic ("coin")
## Cache Notes
- Cache file: `resources/cryptos.csv` (~1,500+ symbols)
- No API calls during queries (instant response)
- Loaded automatically on initialization
- Static snapshot, not real-time
## Error Handling
- Empty cache → Ensure `resources/cryptos.csv` exists
- No results → Try broader terms, check spelling
- Multiple matches → Show all, ask user to clarify
- Symbol format mismatch → Strip `-USD` suffix if needed

View File

@@ -1,4 +1,5 @@
from agno.tools import Toolkit from agno.tools import Toolkit
from app.api.tools.instructions import MARKET_TOOL_INSTRUCTIONS
from app.api.wrapper_handler import WrapperHandler from app.api.wrapper_handler import WrapperHandler
from app.api.core.markets import MarketWrapper, Price, ProductInfo from app.api.core.markets import MarketWrapper, Price, ProductInfo
from app.api.markets import BinanceWrapper, CoinBaseWrapper, CryptoCompareWrapper, YFinanceWrapper from app.api.markets import BinanceWrapper, CoinBaseWrapper, CryptoCompareWrapper, YFinanceWrapper
@@ -29,6 +30,7 @@ class MarketAPIsTool(MarketWrapper, Toolkit):
Toolkit.__init__( # type: ignore Toolkit.__init__( # type: ignore
self, self,
name="Market APIs Toolkit", name="Market APIs Toolkit",
instructions=MARKET_TOOL_INSTRUCTIONS,
tools=[ tools=[
self.get_product, self.get_product,
self.get_products, self.get_products,

View File

@@ -1,4 +1,5 @@
from agno.tools import Toolkit from agno.tools import Toolkit
from app.api.tools.instructions import NEWS_TOOL_INSTRUCTIONS
from app.api.wrapper_handler import WrapperHandler from app.api.wrapper_handler import WrapperHandler
from app.api.core.news import NewsWrapper, Article from app.api.core.news import NewsWrapper, Article
from app.api.news import NewsApiWrapper, GoogleNewsWrapper, CryptoPanicWrapper, DuckDuckGoWrapper from app.api.news import NewsApiWrapper, GoogleNewsWrapper, CryptoPanicWrapper, DuckDuckGoWrapper
@@ -32,6 +33,7 @@ class NewsAPIsTool(NewsWrapper, Toolkit):
Toolkit.__init__( # type: ignore Toolkit.__init__( # type: ignore
self, self,
name="News APIs Toolkit", name="News APIs Toolkit",
instructions=NEWS_TOOL_INSTRUCTIONS,
tools=[ tools=[
self.get_top_headlines, self.get_top_headlines,
self.get_latest_news, self.get_latest_news,

View File

@@ -1,5 +1,6 @@
from agno.tools.toolkit import Toolkit from agno.tools.toolkit import Toolkit
from typing import TypedDict, Literal from typing import TypedDict, Literal
from app.api.tools.instructions import PLAN_MEMORY_TOOL_INSTRUCTIONS
@@ -10,12 +11,12 @@ class Task(TypedDict):
class PlanMemoryTool(Toolkit): class PlanMemoryTool(Toolkit):
def __init__(self): def __init__(self):
self.tasks: list[Task] = [] self.tasks: list[Task] = []
Toolkit.__init__(self, # type: ignore[call-arg] Toolkit.__init__(self, # type: ignore[call-arg]
instructions="Provides stateful, persistent memory for the Team Leader. " \ name="Plan Memory Toolkit",
"This is your primary to-do list and state tracker. " \ instructions=PLAN_MEMORY_TOOL_INSTRUCTIONS,
"Use it to create, execute step-by-step, and record the results of your execution plan.",
tools=[ tools=[
self.add_tasks, self.add_tasks,
self.get_next_pending_task, self.get_next_pending_task,

View File

@@ -1,4 +1,5 @@
from agno.tools import Toolkit from agno.tools import Toolkit
from app.api.tools.instructions import SOCIAL_TOOL_INSTRUCTIONS
from app.api.wrapper_handler import WrapperHandler from app.api.wrapper_handler import WrapperHandler
from app.api.core.social import SocialPost, SocialWrapper from app.api.core.social import SocialPost, SocialWrapper
from app.api.social import * from app.api.social import *
@@ -32,7 +33,8 @@ class SocialAPIsTool(SocialWrapper, Toolkit):
Toolkit.__init__( # type: ignore Toolkit.__init__( # type: ignore
self, self,
name="Socials Toolkit", name="Socials APIs Toolkit",
instructions=SOCIAL_TOOL_INSTRUCTIONS,
tools=[ tools=[
self.get_top_crypto_posts, self.get_top_crypto_posts,
self.get_top_crypto_posts_aggregated, self.get_top_crypto_posts_aggregated,

View File

@@ -5,6 +5,7 @@ import logging
import pandas as pd import pandas as pd
from io import StringIO from io import StringIO
from agno.tools.toolkit import Toolkit from agno.tools.toolkit import Toolkit
from app.api.tools.instructions import SYMBOLS_TOOL_INSTRUCTIONS
logging.basicConfig(level=logging.INFO) logging.basicConfig(level=logging.INFO)
logging = logging.getLogger("crypto_symbols") logging = logging.getLogger("crypto_symbols")
@@ -23,7 +24,7 @@ class CryptoSymbolsTools(Toolkit):
self.final_table = pd.read_csv(self.cache_file) if os.path.exists(self.cache_file) else pd.DataFrame() # type: ignore self.final_table = pd.read_csv(self.cache_file) if os.path.exists(self.cache_file) else pd.DataFrame() # type: ignore
Toolkit.__init__(self, # type: ignore Toolkit.__init__(self, # type: ignore
name="Crypto Symbols Tool", name="Crypto Symbols Tool",
instructions="Tool to get cryptocurrency symbols and search them by name.", instructions=SYMBOLS_TOOL_INSTRUCTIONS,
tools=[ tools=[
self.get_all_symbols, self.get_all_symbols,
self.get_symbols_by_name, self.get_symbols_by_name,