Cortex - 系統架構文檔
專案概述
專案名稱: Cortex
定位: The Cognitive Core for Adaptive AI Agents
核心概念: 模仿大腦皮層架構的 Meta-Agent 平台,能夠動態生成領域特定策略
設計哲學
大腦皮層隱喻
Cortex (大腦皮層) = 高級認知中樞
↓
Prefrontal Cortex (前額葉) → Meta-Agent (策略生成)
Motor Cortex (運動皮層) → Worker Agents (執行任務)
Neural Network (神經網絡) → Multi-agent 協調
核心特性
- Meta-Prompting: Agent 動態生成 VRR (Verify-Reflect-Refine) 策略
- Domain-Agnostic: 核心框架不綁定特定領域
- Self-Improving: 從歷史執行記錄學習優化
- Modular: 可插拔的領域知識和資料源
整體架構
系統層次
┌─────────────────────────────────────────────┐
│ Streamlit UI (Port 8501) │
│ (對話介面 + 圖表視覺化) │
└─────────────────┬───────────────────────────┘
│ HTTP/SSE
┌─────────────────▼───────────────────────────┐
│ Agent API Service (Port 8000) │
│ ┌──────────────────────────────────────┐ │
│ │ Meta-Agent (策略生成中樞) │ │
│ │ ├─ Strategy Generator │ │
│ │ ├─ VRR Engine │ │
│ │ └─ LangGraph Coordinator │ │
│ └──────────────────────────────────────┘ │
│ ┌──────────────────────────────────────┐ │
│ │ Worker Agents │ │
│ │ ├─ Analyzer Agent │ │
│ │ ├─ Calculator Agent │ │
│ │ └─ Verifier Agent │ │
│ └──────────────────────────────────────┘ │
│ ┌──────────────────────────────────────┐ │
│ │ Core Services │ │
│ │ ├─ Gemini LLM │ │
│ │ ├─ RAG Service (Chroma) │ │
│ │ └─ Prompt Manager │ │
│ └──────────────────────────────────────┘ │
└─────────────────┬───────────────────────────┘
│
┌─────────────────▼───────────────────────────┐
│ Data Pipeline Service (Background) │
│ ┌──────────────────────────────────────┐ │
│ │ Stock Data Crawler │ │
│ │ ├─ yfinance Integration │ │
│ │ ├─ APScheduler (定時任務) │ │
│ │ └─ Error Handling & Retry │ │
│ └──────────────────────────────────────┘ │
│ ┌──────────────────────────────────────┐ │
│ │ Technical Indicators Calculator │ │
│ │ ├─ 28 種技術指標計算(62 欄位) │ │
│ │ └─ Batch Processing │ │
│ └──────────────────────────────────────┘ │
└─────────────────┬───────────────────────────┘
│
┌─────────────────▼───────────────────────────┐
│ PostgreSQL Database (Port 5432) │
│ ┌──────────────────────────────────────┐ │
│ │ 股票基本資料 (stocks) │ │
│ │ OHLC 時序資料 (stock_ohlc) │ │
│ │ 技術指標 (technical_indicators) │ │
│ │ Agent 執行歷史 (agent_executions) │ │
│ └──────────────────────────────────────┘ │
└─────────────────────────────────────────────┘
專案結構
cortex/
├── README.md # 專案總覽
├── docker-compose.yml # 服務編排
├── .env.example # 環境變數範本
│
├── core/ # 核心框架 (可複用)
│ ├── __init__.py
│ ├── setup.py # pip install -e ./core
│ │
│ ├── llm/ # LLM 整合層
│ │ ├── __init__.py
│ │ ├── base.py # BaseLLM 抽象類別
│ │ ├── gemini.py # Gemini 實現
│ │ ├── prompt_manager.py # Prompt 模板管理
│ │ └── streaming.py # 串流處理
│ │
│ ├── agent_framework/ # Agent 框架
│ │ ├── __init__.py
│ │ ├── base_agent.py # BaseAgent 基類
│ │ ├── meta_agent.py # Meta-Agent (策略生成)
│ │ ├── vrr_engine.py # VRR 執行引擎
│ │ ├── coordinator.py # LangGraph 協調器
│ │ └── state.py # Agent 狀態管理
│ │
│ ├── knowledge/ # 知識管理
│ │ ├── __init__.py
│ │ ├── vector_store.py # Chroma 抽象層
│ │ ├── rag_service.py # RAG 服務
│ │ └── domain_base.py # 領域知識基類
│ │
│ ├── utils/ # 工具函數
│ │ ├── __init__.py
│ │ ├── config.py # 配置管理
│ │ ├── logging.py # 日誌系統
│ │ └── monitoring.py # 執行監控
│ │
│ └── models/ # 資料模型
│ ├── __init__.py
│ ├── message.py # 訊息模型
│ ├── strategy.py # VRR 策略模型
│ └── agent_state.py # Agent 狀態模型
│
├── investment-agent/ # 投資分析應用
│ ├── README.md
│ ├── requirements.txt
│ │
│ ├── backend/ # FastAPI 後端
│ │ │ # ⚠️ 以下為初期設計草圖,與現行結構有出入:
│ │ │ # 實際 app 入口是 api/main.py、排程入口是 scripts/scheduler.py、
│ │ │ # data_pipeline/crawler.py 已於 #620 移除。
│ │ │ # 現行結構以 CLAUDE.md 與 docs/DATA_PIPELINE_SPEC.md 為準。
│ │ ├── __init__.py
│ │ ├── main.py # FastAPI app 入口
│ │ │
│ │ ├── api/ # API 路由
│ │ │ ├── __init__.py
│ │ │ ├── chat.py # 對話端點
│ │ │ └── stock.py # 股票查詢端點
│ │ │
│ │ ├── agents/ # 領域 Agents
│ │ │ ├── __init__.py
│ │ │ ├── analyzer.py # 股票分析 Agent
│ │ │ ├── calculator.py # 技術指標計算 Agent
│ │ │ ├── verifier.py # 驗證 Agent
│ │ │ └── coordinator.py # LangGraph 工作流程
│ │ │
│ │ ├── data_pipeline/ # 資料管道服務
│ │ │ ├── __init__.py
│ │ │ ├── scheduler.py # APScheduler 定時任務
│ │ │ ├── crawler.py # yfinance 爬蟲
│ │ │ ├── processor.py # 資料處理
│ │ │ └── indicators.py # 技術指標計算
│ │ │
│ │ ├── database/ # 資料庫層
│ │ │ ├── __init__.py
│ │ │ ├── models.py # SQLAlchemy models
│ │ │ ├── crud.py # CRUD 操作
│ │ │ └── init_db.py # 資料庫初始化
│ │ │
│ │ ├── knowledge/ # 投資領域知識
│ │ │ ├── __init__.py
│ │ │ ├── stock_knowledge.py # 股票分析知識庫
│ │ │ └── market_concepts.py # 市場概念
│ │ │
│ │ └── config/ # 配置檔
│ │ ├── markets.yaml # 市場配置
│ │ ├── indicators.yaml # 指標配置
│ │ └── tickers/ # 股票清單
│ │ ├── tw_stocks.txt
│ │ └── us_mag7.txt
│ │
│ ├── streamlit_ui/ # Streamlit 前端
│ │ ├── __init__.py
│ │ ├── app.py # 主應用
│ │ ├── pages/
│ │ │ ├── chat.py # 對話頁面
│ │ │ ├── stock_analysis.py # 股票分析頁面
│ │ │ └── settings.py # 設定頁面
│ │ └── components/
│ │ ├── chart.py # 圖表組件
│ │ └── indicators.py # 指標顯示組件
│ │
│ ├── tests/ # 測試
│ │ ├── unit/
│ │ ├── integration/
│ │ └── e2e/
│ │
│ └── Dockerfile # Docker 配置
│
└── docs/ # 文檔
├── API.md
├── DEPLOYMENT.md
└── DEVELOPMENT.md
技術棧
Backend
- FastAPI: Web 框架 (async, 高性能)
- LangGraph: Multi-agent 編排
- Gemini 1.5: LLM (Flash 日常, Pro 深度分析)
- Chroma: 向量資料庫
- PostgreSQL: 關聯式資料庫
- SQLAlchemy: ORM
- APScheduler: 定時任務
- yfinance: 股票資料
- pandas-ta / ta-lib: 技術指標計算
Frontend
- Streamlit: UI 框架
- Plotly: 互動式圖表
Infrastructure
- Docker & Docker Compose: 容器化
- pytest: 測試框架
核心概念詳解
1. Meta-Agent 架構
傳統 Agent 問題:
固定 Prompt → 一體適用 → 無法適應不同場景
Cortex Meta-Agent:
任務輸入 → Meta-Agent 分析 → 動態生成策略 → 執行 → 驗證
示例:
使用者: "分析台積電的技術面"
Meta-Agent 生成策略:
{
"verify_criteria": [
"RSI 數值範圍 0-100",
"MACD 交叉點識別正確性",
"趨勢判斷邏輯一致性"
],
"reflect_focus": [
"技術指標是否互相印證",
"是否考慮成交量變化"
],
"refine_priority": [
"加強風險提示",
"提供具體數據支持"
]
}
2. VRR (Verify-Reflect-Refine) Engine
三階段循環: 1. Verify: 用 Meta-Agent 生成的標準檢查結果 2. Reflect: 發現問題時深度反思 3. Refine: 基於反思改進輸出
自我改進機制: - 記錄每次執行的驗證結果 - 分析常見失敗模式 - 優化未來的驗證策略
3. LangGraph 工作流程
Stock Analysis Workflow:
# 概念圖 (實際在 INVESTMENT_AGENT_SPEC.md 詳述)
START
↓
Meta-Agent (生成分析策略)
↓
Data Fetcher (獲取股票資料)
↓
Calculator (計算技術指標)
↓
Analyzer (LLM 分析)
↓
Verifier (驗證結果)
↓
[通過?] → END
↓ [不通過]
Reflector (反思問題)
↓
Refiner (改進分析)
↓
Verifier (再次驗證)
↓
END
資料流程
資料更新流程
APScheduler (每天 06:00)
↓
yfinance Crawler
├─ 台灣全部股票 (~1,700支)
└─ 美國七巨頭 (7支)
↓
OHLC Data → PostgreSQL
↓
Indicators Calculator (28 種指標 / 62 欄位)
├─ MA, EMA, RSI, MACD, KD, 布林通道, ATR, ADX, OBV
├─ Williams %R, Volume MA, VWAP, Ichimoku, CCI, MFI
├─ Choppiness, WaveTrend, Aroon, Keltner, Supertrend
└─ Donchian, TII, WVIXF, Elder-Ray, Weis Wave, QQE, SZO, VSA
↓
Technical Indicators → PostgreSQL
Agent 查詢流程
User Query: "分析台積電"
↓
FastAPI Endpoint
↓
Meta-Agent
├─ 生成分析策略
└─ 生成 VRR 標準
↓
Stock Analyzer Agent
├─ 從 DB 讀取 OHLC (2020-now)
├─ 從 DB 讀取技術指標
└─ 結合領域知識 (RAG)
↓
Gemini 1.5 Pro (深度分析)
↓
VRR Engine (驗證)
├─ [通過] → 返回結果
└─ [不通過] → Reflect & Refine
↓
SSE Stream → Streamlit UI
├─ 對話回應
└─ 圖表視覺化
可擴展性設計
1. 新增領域
cortex/
├── core/ # 不變
└── health-agent/ # 新增健康管理 Agent
├── backend/
│ ├── agents/
│ │ ├── symptom_analyzer.py
│ │ └─ ...
│ └── knowledge/
│ └── medical_knowledge.py
└── ...
2. 新增市場
# config/markets.yaml
markets:
taiwan: ...
us: ...
japan: # 新增日本
enabled: true
source: yfinance
suffix: .T
tickers: ...
3. 新增 LLM
# core/llm/claude.py
class ClaudeLLM(BaseLLM):
def __init__(self):
self.client = anthropic.Anthropic(...)
async def generate(self, prompt: str):
# 實現 Claude API
部署架構
Local Development
docker-compose.yml:
- postgres (Port 5432)
- agent-api (Port 8000)
- scheduler (background)
- streamlit (Port 8501)
Future Production (Phase 2)
- Google Cloud Run (配合 Gemini)
- Cloud SQL (PostgreSQL)
- Cloud Scheduler (定時任務)
監控與日誌
Agent 執行記錄
CREATE TABLE agent_executions (
id UUID PRIMARY KEY,
agent_type VARCHAR(50),
task_input JSONB,
strategy JSONB, -- Meta-Agent 生成的策略
result JSONB,
verification_passed BOOLEAN,
execution_time_ms INTEGER,
created_at TIMESTAMP
);
關鍵指標
- Agent 成功率
- 平均執行時間
- VRR 驗證通過率
- 常見失敗模式
測試策略
單元測試
- Core framework: 80%+ 覆蓋率
- LLM 層: Mock Gemini API
- Agent 邏輯: 關鍵路徑測試
整合測試
- End-to-end Agent 工作流程
- 資料管道完整性
- API 端點測試
E2E 測試
- Streamlit UI 互動測試
- 真實股票分析案例
開發階段規劃
Phase 1: MVP (3-4 週)
- ✅ Core framework
- ✅ Investment Agent (單股分析)
- ✅ Data Pipeline (台股全部 + 美股七巨頭)
- ✅ 28 種技術指標(62 欄位)
- ✅ Streamlit UI
- ✅ Local Docker 部署
Phase 2: 優化 (後續)
- 多股比較
- 股票篩選器
- 投資組合分析
- 回測系統
- Health Agent
- Google Cloud 部署
參考資料
- LangGraph: https://langchain-ai.github.io/langgraph/
- Gemini API: https://ai.google.dev/docs
- Chroma: https://docs.trychroma.com/
- yfinance: https://github.com/ranaroussi/yfinance
- Streamlit: https://docs.streamlit.io/
文檔版本: 1.0
最後更新: 2025-02-01
作者: Leon (AI/ML Engineer)