Initial commit: 炼妖壶 (Lianyaohu) - 稷下学宫AI辩论系统

- 🏛️ 稷下学宫八仙论道AI辩论系统
- 🌍 天下体系资本生态分析
- 🔒 安全配置管理 (Doppler集成)
- 📊 RapidAPI永动机数据引擎
- 🎨 Streamlit现代化界面
-  清理所有敏感信息泄露
This commit is contained in:
ben
2025-08-02 16:32:37 +00:00
commit a24b887e8b
110 changed files with 23995 additions and 0 deletions

1
app/__init__.py Normal file
View File

@@ -0,0 +1 @@
# 应用模块

278
app/streamlit_app.py Normal file
View File

@@ -0,0 +1,278 @@
#!/usr/bin/env python3
"""
炼妖壶 (Lianyaohu) - 稷下学宫AI辩论系统
主Streamlit应用入口
重构版本:
- 清晰的模块化结构
- 统一的配置管理
- 安全的密钥处理
"""
import streamlit as st
import sys
from pathlib import Path
# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
def configure_page():
"""配置页面基本设置"""
st.set_page_config(
page_title="炼妖壶 - 稷下学宫AI辩论系统",
page_icon="🏛️",
layout="wide",
initial_sidebar_state="expanded"
)
def show_header():
"""显示页面头部"""
st.title("🏛️ 炼妖壶 - 稷下学宫AI辩论系统")
st.markdown("**基于中国哲学传统的多AI智能体辩论平台**")
# 显示系统状态
col1, col2, col3 = st.columns(3)
with col1:
st.metric("系统状态", "🟢 运行中")
with col2:
st.metric("AI模型", "OpenRouter")
with col3:
st.metric("数据源", "RapidAPI")
def show_sidebar():
"""显示侧边栏"""
with st.sidebar:
st.markdown("## 🎛️ 控制面板")
# 系统信息
st.markdown("### 📊 系统信息")
st.info("**版本**: v2.0 (重构版)")
st.info("**状态**: 迁移完成")
# 配置检查
st.markdown("### 🔧 配置状态")
try:
from config.doppler_config import validate_config
if validate_config():
st.success("✅ 配置正常")
else:
st.error("❌ 配置异常")
except Exception as e:
st.warning(f"⚠️ 配置检查失败: {str(e)}")
# 快速操作
st.markdown("### ⚡ 快速操作")
if st.button("🧪 测试API连接"):
test_api_connections()
if st.button("🏛️ 启动八仙论道"):
start_jixia_debate()
if st.button("🚀 启动Swarm论道"):
start_swarm_debate()
def test_api_connections():
"""测试API连接"""
with st.spinner("正在测试API连接..."):
try:
from scripts.test_openrouter_api import test_openrouter_api, test_rapidapi_connection
openrouter_ok = test_openrouter_api()
rapidapi_ok = test_rapidapi_connection()
if openrouter_ok and rapidapi_ok:
st.success("✅ 所有API连接正常")
else:
st.error("❌ 部分API连接失败")
except Exception as e:
st.error(f"❌ API测试异常: {str(e)}")
def start_jixia_debate():
"""启动稷下学宫辩论"""
with st.spinner("正在启动稷下学宫八仙论道..."):
try:
from config.doppler_config import get_rapidapi_key
from src.jixia.engines.perpetual_engine import JixiaPerpetualEngine
api_key = get_rapidapi_key()
engine = JixiaPerpetualEngine(api_key)
# 运行辩论
results = engine.simulate_jixia_debate('TSLA')
st.success("✅ 八仙论道完成")
st.json(results)
except Exception as e:
st.error(f"❌ 辩论启动失败: {str(e)}")
def start_swarm_debate():
"""启动Swarm八仙论道"""
with st.spinner("正在启动Swarm八仙论道..."):
try:
import asyncio
from src.jixia.debates.swarm_debate import start_ollama_debate, start_openrouter_debate
# 选择模式
mode = st.session_state.get('swarm_mode', 'ollama')
topic = st.session_state.get('swarm_topic', 'TSLA股价走势分析')
# 构建上下文
context = {
"market_sentiment": "谨慎乐观",
"volatility": "中等",
"technical_indicators": {
"RSI": 65,
"MACD": "金叉",
"MA20": "上穿"
}
}
# 运行辩论
if mode == 'ollama':
result = asyncio.run(start_ollama_debate(topic, context))
else:
result = asyncio.run(start_openrouter_debate(topic, context))
if result:
st.success("✅ Swarm八仙论道完成")
st.json(result)
else:
st.error("❌ Swarm辩论失败")
except Exception as e:
st.error(f"❌ Swarm辩论启动失败: {str(e)}")
def main():
"""主函数"""
configure_page()
show_header()
show_sidebar()
# 主内容区域
st.markdown("---")
# 选项卡
tab1, tab2, tab3 = st.tabs(["🏛️ 稷下学宫", "🌍 天下体系", "📊 数据分析"])
with tab1:
st.markdown("### 🏛️ 稷下学宫 - 八仙论道")
st.markdown("**多AI智能体辩论系统基于中国传统八仙文化**")
# 辩论模式选择
debate_mode = st.selectbox(
"选择辩论模式",
["传统模式 (RapidAPI数据)", "Swarm模式 (AI智能体)"],
key="debate_mode_select"
)
if debate_mode == "Swarm模式 (AI智能体)":
# Swarm模式配置
col1, col2 = st.columns(2)
with col1:
swarm_mode = st.selectbox(
"AI服务模式",
["ollama", "openrouter"],
key="swarm_mode_select"
)
st.session_state.swarm_mode = swarm_mode
with col2:
swarm_topic = st.text_input(
"辩论主题",
value="英伟达股价走势AI泡沫还是技术革命",
key="swarm_topic_input"
)
st.session_state.swarm_topic = swarm_topic
if st.button("🚀 启动Swarm八仙论道", type="primary"):
start_swarm_debate()
else:
# 传统模式
col1, col2 = st.columns([2, 1])
with col1:
topic = st.text_input("辩论主题 (股票代码)", value="TSLA", key="debate_topic")
with col2:
if st.button("🎭 开始辩论", type="primary"):
start_debate_session(topic)
# 显示辩论历史
if 'debate_history' in st.session_state:
st.markdown("#### 📜 辩论记录")
for record in st.session_state.debate_history[-3:]: # 显示最近3次
with st.expander(f"🎭 {record['topic']} - {record['time']}"):
st.json(record['results'])
with tab2:
st.markdown("### 🌍 天下体系分析")
try:
from app.tabs.tianxia_tab import render_tianxia_tab
render_tianxia_tab()
except Exception as e:
st.error(f"❌ 天下体系模块加载失败: {str(e)}")
with tab3:
st.markdown("### 📊 数据分析")
st.info("🚧 数据分析模块开发中...")
# 显示系统统计
try:
from config.doppler_config import get_rapidapi_key
from src.jixia.engines.perpetual_engine import JixiaPerpetualEngine
api_key = get_rapidapi_key()
engine = JixiaPerpetualEngine(api_key)
stats = engine.get_usage_stats()
col1, col2, col3 = st.columns(3)
with col1:
st.metric("API调用总数", stats['total_calls'])
with col2:
st.metric("活跃API数", f"{stats['active_apis']}/{stats['total_apis']}")
with col3:
st.metric("未使用API", stats['unused_count'])
except Exception as e:
st.warning(f"⚠️ 无法加载统计数据: {str(e)}")
def start_debate_session(topic: str):
"""启动辩论会话"""
if not topic:
st.error("请输入辩论主题")
return
with st.spinner(f"🏛️ 八仙正在就 {topic} 展开论道..."):
try:
from config.doppler_config import get_rapidapi_key
from src.jixia.engines.perpetual_engine import JixiaPerpetualEngine
from datetime import datetime
api_key = get_rapidapi_key()
engine = JixiaPerpetualEngine(api_key)
# 运行辩论
results = engine.simulate_jixia_debate(topic)
# 保存到会话状态
if 'debate_history' not in st.session_state:
st.session_state.debate_history = []
st.session_state.debate_history.append({
'topic': topic,
'time': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
'results': {name: {'success': result.success, 'api_used': result.api_used}
for name, result in results.items()}
})
st.success(f"✅ 八仙论道完成!共有 {len(results)} 位仙人参与")
# 显示结果摘要
successful_debates = sum(1 for result in results.values() if result.success)
st.info(f"📊 成功获取数据: {successful_debates}/{len(results)} 位仙人")
except Exception as e:
st.error(f"❌ 辩论启动失败: {str(e)}")
if __name__ == "__main__":
main()

436
app/tabs/tianxia_tab.py Normal file
View File

@@ -0,0 +1,436 @@
"""
天下体系 - 儒门天下观资本生态分析Tab
基于"天命树"结构模型分析全球资本市场权力结构
重构版本:
- 移除硬编码API密钥
- 使用统一配置管理
- 改进数据结构
- 增强错误处理
"""
import streamlit as st
import pandas as pd
import plotly.express as px
from datetime import datetime
import time
import random
from typing import Dict, List, Any, Optional
from dataclasses import dataclass
# 导入配置管理
try:
from config.doppler_config import get_rapidapi_key
except ImportError:
# 如果配置模块不可用,使用环境变量
import os
def get_rapidapi_key():
return os.getenv('RAPIDAPI_KEY', '')
@dataclass
class StockEntity:
"""股票实体数据类"""
symbol: str
name: str
role: str
dependency: Optional[str] = None
serves: Optional[str] = None
type: Optional[str] = None
@dataclass
class EcosystemData:
"""生态系统数据类"""
tianzi: Dict[str, str]
dafu: List[StockEntity]
shi: List[StockEntity]
jiajie: List[StockEntity]
class TianxiaAnalyzer:
"""天下体系分析器 - 天命树结构分析"""
def __init__(self):
"""初始化分析器"""
try:
self.rapidapi_key = get_rapidapi_key()
except Exception:
self.rapidapi_key = ""
st.warning("⚠️ 未配置RapidAPI密钥将使用模拟数据")
# 定义三大天命树生态系统
self.ecosystems = self._initialize_ecosystems()
def _initialize_ecosystems(self) -> Dict[str, EcosystemData]:
"""初始化生态系统数据"""
return {
'AI': EcosystemData(
tianzi={'symbol': 'NVDA', 'name': 'NVIDIA', 'tianming': 'CUDA + GPU硬件定义AI计算范式'},
dafu=[
StockEntity('TSM', 'TSMC', '芯片代工', '高端芯片唯一代工厂'),
StockEntity('000660.SZ', 'SK Hynix', 'HBM内存', 'GPU性能关键'),
StockEntity('MU', 'Micron', 'HBM内存', 'GPU性能关键'),
StockEntity('SMCI', 'Supermicro', '服务器集成', 'GPU转化为计算能力')
],
shi=[
StockEntity('ASML', 'ASML', '光刻设备', serves='TSMC'),
StockEntity('AMAT', 'Applied Materials', '半导体设备', serves='TSMC')
],
jiajie=[
StockEntity('AMD', 'AMD', '竞争对手', type='竞争天子'),
StockEntity('GOOGL', 'Google', '云计算', type='云计算天子'),
StockEntity('AMZN', 'Amazon', '云计算', type='云计算天子')
]
),
'EV': EcosystemData(
tianzi={'symbol': 'TSLA', 'name': 'Tesla', 'tianming': '软件定义汽车 + 超级充电网络'},
dafu=[
StockEntity('300750.SZ', 'CATL', '动力电池', '动力系统基石'),
StockEntity('6752.T', 'Panasonic', '动力电池', '动力系统基石'),
StockEntity('ALB', 'Albemarle', '锂矿', '源头命脉'),
StockEntity('002460.SZ', 'Ganfeng Lithium', '锂矿', '源头命脉')
],
shi=[
StockEntity('002497.SZ', 'Yahua Industrial', '氢氧化锂', serves='CATL'),
StockEntity('002850.SZ', 'Kedali', '精密结构件', serves='CATL')
],
jiajie=[
StockEntity('002594.SZ', 'BYD', '电动车', type='诸侯'),
StockEntity('VWAGY', 'Volkswagen', '传统车企', type='诸侯'),
StockEntity('F', 'Ford', '传统车企', type='诸侯')
]
),
'Consumer_Electronics': EcosystemData(
tianzi={'symbol': 'AAPL', 'name': 'Apple', 'tianming': 'iOS + App Store生态系统'},
dafu=[
StockEntity('2317.TW', 'Foxconn', '代工制造', '物理执行者'),
StockEntity('TSM', 'TSMC', '芯片代工', '性能优势保障'),
StockEntity('005930.KS', 'Samsung Display', '屏幕供应', '显示技术'),
StockEntity('QCOM', 'Qualcomm', '基带芯片', '通信命脉')
],
shi=[
StockEntity('002475.SZ', 'Luxshare', '精密制造', serves='Foxconn'),
StockEntity('002241.SZ', 'Goertek', '声学器件', serves='Foxconn')
],
jiajie=[
StockEntity('005930.KS', 'Samsung', '手机制造', type='亦敌亦友天子'),
StockEntity('1810.HK', 'Xiaomi', '手机制造', type='诸侯'),
StockEntity('NVDA', 'NVIDIA', 'AI芯片', type='跨生态天子')
]
)
}
def get_stock_data(self, symbol: str) -> Dict[str, Any]:
"""
获取股票数据
Args:
symbol: 股票代码
Returns:
股票数据字典
"""
# TODO: 实现真实API调用
# 目前使用模拟数据
try:
return {
'price': round(random.uniform(50, 500), 2),
'change_pct': round(random.uniform(-5, 5), 2),
'market_cap': f"{random.randint(100, 3000)}B",
'volume': random.randint(1000000, 100000000)
}
except Exception:
return {
'price': 'N/A',
'change_pct': 0,
'market_cap': 'N/A',
'volume': 'N/A'
}
def create_tianming_card(self, ecosystem_name: str, ecosystem_data: EcosystemData) -> None:
"""
创建天命卡片
Args:
ecosystem_name: 生态系统名称
ecosystem_data: 生态系统数据
"""
tianzi = ecosystem_data.tianzi
stock_data = self.get_stock_data(tianzi['symbol'])
st.markdown(f"### 👑 {ecosystem_name} 天命树")
# 天子信息
col1, col2, col3 = st.columns([1, 2, 1])
with col1:
st.markdown("#### 🌟 天子")
st.markdown(f"**{tianzi['name']}** ({tianzi['symbol']})")
with col2:
st.markdown("#### 📜 天命")
st.info(tianzi['tianming'])
with col3:
st.metric(
label="股价",
value=f"${stock_data['price']}",
delta=f"{stock_data['change_pct']:+.2f}%"
)
# 大夫层级
if ecosystem_data.dafu:
st.markdown("#### 🏛️ 大夫 (核心依赖)")
dafu_cols = st.columns(min(len(ecosystem_data.dafu), 4))
for i, dafu in enumerate(ecosystem_data.dafu):
col_index = i % 4
with dafu_cols[col_index]:
data = self.get_stock_data(dafu.symbol)
st.metric(
label=f"{dafu.name}",
value=f"${data['price']}",
delta=f"{data['change_pct']:+.2f}%"
)
st.caption(f"**{dafu.role}**: {dafu.dependency}")
# 士层级
if ecosystem_data.shi:
st.markdown("#### ⚔️ 士 (专业供应商)")
shi_cols = st.columns(min(len(ecosystem_data.shi), 3))
for i, shi in enumerate(ecosystem_data.shi):
col_index = i % 3
with shi_cols[col_index]:
data = self.get_stock_data(shi.symbol)
st.metric(
label=f"{shi.name}",
value=f"${data['price']}",
delta=f"{data['change_pct']:+.2f}%"
)
st.caption(f"**{shi.role}** → 服务于{shi.serves}")
# 嫁接关系
if ecosystem_data.jiajie:
st.markdown("#### 🔗 嫁接关系 (跨生态链接)")
jiajie_cols = st.columns(min(len(ecosystem_data.jiajie), 4))
for i, jiajie in enumerate(ecosystem_data.jiajie):
col_index = i % 4
with jiajie_cols[col_index]:
data = self.get_stock_data(jiajie.symbol)
st.metric(
label=f"{jiajie.name}",
value=f"${data['price']}",
delta=f"{data['change_pct']:+.2f}%"
)
st.caption(f"**{jiajie.type}**")
st.markdown("---")
def create_tianming_tree_table(self) -> pd.DataFrame:
"""
创建天命树完整表格 - 用于投资组合去相关性分析
Returns:
包含所有股票信息的DataFrame
"""
st.markdown("### 📋 天命树完整表格 - 投资组合去相关性分析")
st.markdown("**核心理念**: 投资组合的本质是去相关性 - 从不同root下的不同spine下的不同leaf进行配置")
all_stocks = []
for eco_name, eco_data in self.ecosystems.items():
# 天子
tianzi = eco_data.tianzi
stock_data = self.get_stock_data(tianzi['symbol'])
all_stocks.append({
'Root': eco_name,
'Level': '👑 天子',
'Symbol': tianzi['symbol'],
'Company': tianzi['name'],
'Role': '定义范式',
'Dependency_Path': f"{eco_name}",
'Price': stock_data['price'],
'Change%': stock_data['change_pct'],
'Market_Cap': stock_data['market_cap'],
'Correlation_Risk': '极高 - 生态核心'
})
# 大夫
for dafu in eco_data.dafu:
stock_data = self.get_stock_data(dafu.symbol)
all_stocks.append({
'Root': eco_name,
'Level': '🏛️ 大夫',
'Symbol': dafu.symbol,
'Company': dafu.name,
'Role': dafu.role,
'Dependency_Path': f"{eco_name}{tianzi['name']}{dafu.name}",
'Price': stock_data['price'],
'Change%': stock_data['change_pct'],
'Market_Cap': stock_data['market_cap'],
'Correlation_Risk': '高 - 深度绑定天子'
})
# 士
for shi in eco_data.shi:
stock_data = self.get_stock_data(shi.symbol)
all_stocks.append({
'Root': eco_name,
'Level': '⚔️ 士',
'Symbol': shi.symbol,
'Company': shi.name,
'Role': shi.role,
'Dependency_Path': f"{eco_name}{shi.serves}{shi.name}",
'Price': stock_data['price'],
'Change%': stock_data['change_pct'],
'Market_Cap': stock_data['market_cap'],
'Correlation_Risk': '中 - 专业供应商'
})
# 嫁接
for jiajie in eco_data.jiajie:
stock_data = self.get_stock_data(jiajie.symbol)
all_stocks.append({
'Root': '🔗 跨生态',
'Level': '🔗 嫁接',
'Symbol': jiajie.symbol,
'Company': jiajie.name,
'Role': jiajie.type or jiajie.role,
'Dependency_Path': f"多生态嫁接 → {jiajie.name}",
'Price': stock_data['price'],
'Change%': stock_data['change_pct'],
'Market_Cap': stock_data['market_cap'],
'Correlation_Risk': '低 - 多元化依赖'
})
df = pd.DataFrame(all_stocks)
# 显示表格
st.dataframe(
df,
use_container_width=True,
column_config={
"Root": st.column_config.TextColumn("生态根节点", width="small"),
"Level": st.column_config.TextColumn("层级", width="small"),
"Symbol": st.column_config.TextColumn("代码", width="small"),
"Company": st.column_config.TextColumn("公司", width="medium"),
"Role": st.column_config.TextColumn("角色", width="medium"),
"Dependency_Path": st.column_config.TextColumn("依赖路径", width="large"),
"Price": st.column_config.NumberColumn("股价", format="$%.2f"),
"Change%": st.column_config.NumberColumn("涨跌幅", format="%.2f%%"),
"Market_Cap": st.column_config.TextColumn("市值", width="small"),
"Correlation_Risk": st.column_config.TextColumn("相关性风险", width="medium")
}
)
return df
def render_tianxia_tab() -> None:
"""渲染天下体系Tab"""
# 页面标题
st.markdown("### 🏛️ 天下体系 - 儒门天下观资本生态分析")
st.markdown("**基于'天命树'结构模型,穿透市场表象,绘制全球资本市场真实的权力结构**")
st.markdown("---")
# 初始化分析器
analyzer = TianxiaAnalyzer()
# 控制面板
col1, col2, col3 = st.columns([1, 1, 2])
with col1:
auto_refresh = st.checkbox("🔄 自动刷新", value=False, key="tianxia_auto_refresh")
with col2:
if st.button("🏛️ 扫描天下", type="primary", key="tianxia_scan_btn"):
st.session_state.trigger_tianxia_scan = True
with col3:
st.markdown("*正在分析全球资本生态权力结构...*")
# 理论介绍
with st.expander("📚 天命树理论基础"):
st.markdown("""
### 🏛️ 儒门天下观核心思想
**两大哲学基石:**
1. **结构非平权**: 资本宇宙本质是不平权的、层级森严的树状结构
2. **天命与脉络**: 每个生态都有唯一的"根节点"(天子),拥有定义整个生态的"天命"
**四层架构:**
- **👑 天子**: 定义范式的平台型公司 (如Apple, NVIDIA, Tesla)
- **🏛️ 大夫**: 深度绑定天子的核心供应商 (如TSMC, CATL)
- **⚔️ 士**: 专业供应商和服务商 (如ASML, Luxshare)
- **🔗 嫁接**: 跨生态的策略性链接关系
""")
# 自动刷新逻辑
if auto_refresh:
time.sleep(60)
st.rerun()
# 触发扫描或显示数据
if st.session_state.get('trigger_tianxia_scan', False) or 'tianxia_scan_time' not in st.session_state:
with st.spinner("🏛️ 正在扫描天下体系..."):
st.session_state.tianxia_scan_time = datetime.now()
st.session_state.trigger_tianxia_scan = False
# 显示扫描时间
if 'tianxia_scan_time' in st.session_state:
st.info(f"📅 最后扫描时间: {st.session_state.tianxia_scan_time.strftime('%Y-%m-%d %H:%M:%S')}")
# 显示三大生态系统
st.markdown("## 🌍 三大天命树生态系统")
# 分析模式选择
analysis_mode = st.selectbox(
"选择分析模式",
["生态系统分析", "投资组合去相关性分析"],
key="tianxia_analysis_mode"
)
if analysis_mode == "生态系统分析":
# 生态系统选择
selected_ecosystem = st.selectbox(
"选择要分析的生态系统",
["全部", "AI", "EV", "Consumer_Electronics"],
format_func=lambda x: {
"全部": "🌍 全部生态系统",
"AI": "🤖 AI人工智能生态",
"EV": "⚡ 电动汽车生态",
"Consumer_Electronics": "📱 消费电子生态"
}[x],
key="tianxia_ecosystem_select"
)
if selected_ecosystem == "全部":
# 显示所有生态系统
for eco_name, eco_data in analyzer.ecosystems.items():
analyzer.create_tianming_card(eco_name, eco_data)
else:
# 显示选定的生态系统
analyzer.create_tianming_card(selected_ecosystem, analyzer.ecosystems[selected_ecosystem])
else: # 投资组合去相关性分析
st.markdown("## 🎯 投资组合去相关性分析")
st.info("**核心理念**: 真正的分散投资是从不同的root天子下的不同spine大夫下的不同leaf进行配置")
# 创建完整天命树表格
df = analyzer.create_tianming_tree_table()
# 页面底部说明
st.markdown("---")
st.markdown("""
### 🎯 天下体系核心洞察
**权力结构分析**
- **AI生态**: NVIDIA通过CUDA平台统治AI计算TSMC是关键"嫁接"节点
- **电动车生态**: Tesla定义软件汽车范式CATL掌握电池命脉
- **消费电子生态**: Apple建立iOS护城河供应链高度集中化
**投资策略启示**
1. **投资天子**: 寻找定义范式的平台型公司
2. **关注大夫**: 深度绑定天子的核心供应商往往被低估
3. **警惕嫁接**: 被多个天子"嫁接"的公司风险与机会并存
4. **避开士层**: 缺乏议价能力的专业供应商投资价值有限
⚠️ **免责声明**: 天下体系分析仅供参考,投资有风险,决策需谨慎!
""")