Merge optimization changes into main

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
This commit is contained in:
MarkLo127 2026-03-12 18:50:01 +08:00
commit a019896a9e
3 changed files with 45 additions and 44 deletions

View File

@ -40,7 +40,7 @@ class HybridTaskManager:
self._lock = threading.RLock()
self._cleanup_interval = 3600 # 1 hour
self._task_expiry = 86400 # 24 hours for pending/running tasks
self._completed_task_expiry = 3600 # 1 hour for completed/failed tasks (auto cleanup)
self._completed_task_expiry = 14400 # 4 hours for completed/failed tasks (auto cleanup) — give users time to save reports
# Check Redis availability on startup
if is_redis_available():

View File

@ -80,12 +80,12 @@ def validate_and_warn(content: str, agent_name: str) -> list:
context = content[max(0, idx-15):min(len(content), idx+15)]
warnings.append(f"Suspicious '' character found. Context: ...{context}...")
# Check word count
# Check word count (500-1000 range)
word_count = count_chinese_words(content)
if word_count < 800:
warnings.append(f"Too short: {word_count} words (expected 800-1500)")
elif word_count > 1500:
warnings.append(f"Too long: {word_count} words (expected 800-1500)")
if word_count < 500:
warnings.append(f"⚠️ Report too short (below 500 words)")
elif word_count > 1000:
warnings.append(f"⚠️ Report too long (exceeds 1000 words)")
# Check for truncation markers that shouldn't be there
truncation_markers = ['...(已截斷)', '...(內容已截斷)', '...(為控制長度已精簡)']
@ -119,37 +119,38 @@ def post_process_agent_output(content: str, agent_name: str, retry_callback=None
# Step 2: Validate and warn
warnings = validate_and_warn(content, agent_name)
# Step 3: Critical validation - retry if needed
# Step 3: Critical validation - retry if needed (500-1000 range)
word_count = count_chinese_words(content)
if (word_count < 800 or word_count > 1500) and retry_callback:
print(f"\n🔄 {agent_name}: Word count {word_count} out of range, triggering retry...")
if (word_count < 500 or word_count > 1000) and retry_callback:
print(f"\n🔄 {agent_name}: Word count out of range, triggering retry...")
# Callback should regenerate the content
# This is optional and should be implemented in the calling code
return content
def ensure_min_length(content: str, min_words: int = 800, agent_name: str = "Agent") -> tuple:
def ensure_min_length(content: str, min_words: int = 500, agent_name: str = "Agent") -> tuple:
"""
確保報告達到最小字數如果不夠則返回False觸發重試
確保報告達到字數要求範圍 (500-1000)如果不符合則返回False觸發重試
Args:
content: The report content to check
min_words: Minimum required word count (default: 800)
min_words: Minimum required word count (default: 500)
agent_name: Name of the agent for logging
Returns:
tuple: (content, is_valid: bool)
"""
word_count = count_chinese_words(content)
max_words = 1000
if word_count < min_words:
print(f"⚠️ [{agent_name}] 報告字數不足: {word_count}字 < {min_words}字最低要求")
print(f"⚠️ [{agent_name}] Report too short")
return content, False
elif word_count > 1500:
print(f"⚠️ [{agent_name}] 報告字數過多: {word_count}字 > 1500字上限")
elif word_count > max_words:
print(f"⚠️ [{agent_name}] Report too long")
return content, False
else:
print(f"✅ [{agent_name}] 報告字數符合要求: {word_count}")
print(f"✅ [{agent_name}] Report meets requirements")
return content, True

View File

@ -92,13 +92,13 @@ You are a senior technical analyst responsible for providing precise market tech
Integrate data to provide professional insights
Report Structure
**Word Count**: 800-1500 words (excluding tables)
**Word Count**: 500-1000 words (excluding tables)
**Content Structure**:
1. Market Overview (120-150 words): Trend direction and momentum
2. Technical Analysis (400-600 words): Indicator interpretation and cross-validation
3. Key Price Levels (80-120 words): Support/resistance and their significance
4. Trading Strategy (150-200 words): Entry points, stop-loss, target prices
1. Market Overview (60-80 words): Trend direction and momentum
2. Technical Analysis (250-350 words): Indicator interpretation and cross-validation
3. Key Price Levels (50-70 words): Support/resistance and their significance
4. Trading Strategy (100-150 words): Entry points, stop-loss, target prices
5. Data Summary Table (required)
**Closing**:
@ -123,13 +123,13 @@ Please provide a professional, precise, and actionable technical analysis report
整合數據後提出專業見解
報告架構
**字數要求**800-1500不含表格
**字數要求**500-1000不含表格
**內容結構**
1. 市場概況120-150趨勢方向與動能強弱
2. 技術分析400-600指標解讀與相互驗證
3. 關鍵價位80-120支撐/壓力位及其技術意義
4. 操作策略150-200進場點位停損設定目標價位
1. 市場概況60-80趨勢方向與動能強弱
2. 技術分析250-350指標解讀與相互驗證
3. 關鍵價位50-70支撐/壓力位及其技術意義
4. 操作策略100-150進場點位停損設定目標價位
5. 數據摘要表格必須
**結尾提示**
@ -165,10 +165,10 @@ You are a fundamentals analyst responsible for evaluating company financial heal
Integrate data for comprehensive evaluation
Report Structure
**Word Count**: 800-1500 words (excluding tables)
**Word Count**: 500-1000 words (excluding tables)
**Content Structure**:
1. Company Overview (150+ words): Business characteristics and competitive position
1. Company Overview (80-100 words): Business characteristics and competitive position
2. Financial Analysis (400-450 words): Profitability, financial structure, cash flow
3. Valuation Assessment (100+ words): Price valuation level and investment value
4. Investment Recommendation (150+ words): Fundamental-based trading suggestions
@ -196,13 +196,13 @@ Please provide a professional and comprehensive fundamental analysis report with
整合數據進行綜合評估
報告架構
**字數要求**800-1500不含表格
**字數要求**500-1000不含表格
**內容結構**
1. 公司概述150字以上業務特性與競爭地位
2. 財務分析400-450獲利能力財務結構現金流分析
3. 估值研判100字以上股價評價水準與投資價值
4. 投資建議150字以上基於基本面的操作建議
1. 公司概述80-100業務特性與競爭地位
2. 財務分析250-300獲利能力財務結構現金流分析
3. 估值研判60-80股價評價水準與投資價值
4. 投資建議100-120基於基本面的操作建議
5. 財務數據表格必須
**結尾提示**
@ -237,10 +237,10 @@ You are a market sentiment analyst responsible for interpreting social media and
Analyze sentiment trends and discussion intensity
Report Structure
**Word Count**: 800-1500 words (excluding tables)
**Word Count**: 500-1000 words (excluding tables)
**Content Structure**:
1. Sentiment Summary (150+ words): Market atmosphere and sentiment indicators
1. Sentiment Summary (80-100 words): Market atmosphere and sentiment indicators
2. Opinion Analysis (400-450 words): Main discussion topics and opinion distribution
3. Key Insights (100+ words): Sentiment extremes or turning signals
4. Investment Implications (150+ words): Sentiment-based trading strategy insights
@ -267,10 +267,10 @@ Please provide a professional and insightful market sentiment analysis report wi
分析輿情傾向與討論熱度
報告架構
**字數要求**800-1500不含表格
**字數要求**500-1000不含表格
**內容結構**
1. 情緒概要150字以上市場氛圍與情緒指標
1. 情緒概要80-100市場氛圍與情緒指標
2. 輿情分析400-450主要討論議題與觀點分布
3. 關鍵洞察100字以上情緒極值或轉折訊號
4. 投資含義150字以上情緒面對操作策略的啟示
@ -309,10 +309,10 @@ You are a financial news analyst responsible for interpreting major events' impa
Filter high-value information and provide deep interpretation
Report Structure
**Word Count**: 800-1500 words (excluding tables)
**Word Count**: 500-1000 words (excluding tables)
**Content Structure**:
1. News Summary (120-150 words): Key event overview
1. News Summary (60-80 words): Key event overview
2. Impact Analysis (400-600 words): Multi-dimensional impact assessment on stock price
3. Risk Alerts (80-120 words): Potential risks or overlooked factors
4. Trading Suggestions (150-200 words): News-based investment strategy
@ -340,10 +340,10 @@ Please provide a professional and insightful news analysis report with a Markdow
篩選高價值資訊並進行深度解讀
報告架構
**字數要求**800-1500不含表格
**字數要求**500-1000不含表格
**內容結構**
1. 新聞摘要120-150重點事件概述
1. 新聞摘要60-80重點事件概述
2. 影響分析400-600事件對股價的多維度影響評估
3. 風險提示80-120潛在風險或市場未注意的因素
4. 操作建議150-200基於新聞面的投資策略