hiroshi57/OpenMythos
GitHub: hiroshi57/OpenMythos
基于循环深度 Transformer 架构的 OpenAI 兼容 LLM 服务框架,通过 127 个 REST API 提供推理、RAG、Agent、多模态、训练评估及安全扫描等全栈 AI 能力。
Stars: 0 | Forks: 0
# OpenMythos
OpenMythos
cd OpenMythos
# 2. 環境変数を設定
cp .env.example .env
# .env を編集して API_KEY を設定してください
# 3. 起動
docker compose up --build -d
# 4. 動作確認
curl http://localhost:8000/health
# → {"status":"ok","version":"0.57.0"}
# 5. APIドキュメントをブラウザで確認
open http://localhost:8000/docs
```
### 方法2:本地直接启动
```
# 依存関係インストール
pip install -r requirements.txt
pip install fastapi uvicorn gunicorn
# サーバー起動(開発モード)
uvicorn serve.api:app --host 0.0.0.0 --port 8000 --reload
# サーバー起動(本番モード)
gunicorn serve.api:app \
--workers 2 \
--worker-class uvicorn.workers.UvicornWorker \
--bind 0.0.0.0:8000
```
## 认证配置 / Authentication
```
# .env または環境変数で設定
API_KEY=your-secret-key-here
# リクエスト時は Bearer Token を付与
curl http://localhost:8000/v1/chat/completions \
-H "Authorization: Bearer your-secret-key-here" \
-H "Content-Type: application/json" \
-d '{"model":"openmythos","messages":[{"role":"user","content":"こんにちは"}]}'
```
## 主要 API 的使用方法
### 聊天(兼容 OpenAI)
```
import requests
BASE = "http://localhost:8000"
HDR = {"Authorization": "Bearer your-key", "Content-Type": "application/json"}
resp = requests.post(f"{BASE}/v1/chat/completions", headers=HDR, json={
"model": "openmythos",
"messages": [
{"role": "system", "content": "あなたは丁寧なアシスタントです。"},
{"role": "user", "content": "機械学習とは何ですか?"},
],
"max_tokens": 256,
})
print(resp.json()["choices"][0]["message"]["content"])
```
### Assistants API(线程对话)
```
# 1. アシスタント作成
asst = requests.post(f"{BASE}/v1/assistants", headers=HDR, json={
"name": "SupportBot",
"instructions": "あなたは社内サポートデスクです。丁寧に回答してください。"
}).json()
# 2. スレッド作成
thread = requests.post(f"{BASE}/v1/threads", headers=HDR, json={}).json()
# 3. ユーザーメッセージ追加
requests.post(f"{BASE}/v1/threads/{thread['id']}/messages", headers=HDR, json={
"role": "user", "content": "有給休暇の申請方法を教えてください"
})
# 4. 実行
run = requests.post(f"{BASE}/v1/threads/{thread['id']}/runs", headers=HDR, json={
"assistant_id": asst["id"]
}).json()
# 5. 返答を取得
msgs = requests.get(f"{BASE}/v1/threads/{thread['id']}/messages", headers=HDR).json()
for m in msgs["data"]:
print(f"[{m['role']}] {m['content'][0]['text']['value']}")
```
### RAG(内部文档搜索)
```
# ドキュメントを登録
requests.post(f"{BASE}/v1/rag/index", headers=HDR, json={
"documents": [
"有給休暇は年間20日付与されます。申請はHRシステムから行ってください。",
"経費精算は月末締めです。領収書は3ヶ月以内に提出してください。",
],
"session_id": "company-handbook"
})
# 検索
result = requests.post(f"{BASE}/v1/rag", headers=HDR, json={
"query": "有給休暇の申請方法",
"session_id": "company-handbook"
}).json()
print(result["answer"])
```
### 安全扫描
```
# Webアプリ脆弱性スキャン
report = requests.post(f"{BASE}/v1/security/scan", headers=HDR, json={
"target_url": "https://your-app.example.com",
"timeout": 10.0
}).json()
print(f"リスクスコア: {report['risk_score']:.1f}/10.0")
print(f"検出件数: {len(report['findings'])}")
# Markdownレポート生成
md = requests.post(f"{BASE}/v1/security/report/md", headers=HDR, json={
"target_url": "https://your-app.example.com"
}).json()["markdown"]
```
### 向量数据库
```
# 文書を登録
requests.post(f"{BASE}/v1/vector-store/upsert", headers=HDR, json={
"id": "doc-001",
"text": "OpenMythosはRDTアーキテクチャを採用しています",
"metadata": {"source": "technical-docs", "team": "engineering"}
})
# 類似検索
results = requests.post(f"{BASE}/v1/vector-store/query", headers=HDR, json={
"query": "アーキテクチャの特徴",
"top_k": 5
}).json()
```
## 所有 API endpoint 列表
### 核心 (Core)
| Method | Path | 描述 |
|--------|------|------|
| GET | `/health` | 健康检查 |
| GET | `/metrics` | Prometheus 指标 |
| POST | `/v1/chat/completions` | 兼容 OpenAI 的聊天补全 |
| POST | `/v1/completions` | 文本补全 |
| POST | `/v1/embeddings` | embedding 向量生成 |
| POST | `/v1/semantic-search` | 语义搜索 |
| POST | `/v1/batch` | 批量推理 |
### Assistants API(兼容 OpenAI)
| Method | Path | 描述 |
|--------|------|------|
| POST/GET | `/v1/assistants` | 创建、列出 Assistant |
| GET/DELETE | `/v1/assistants/{id}` | 获取、删除 Assistant |
| POST/GET/DELETE | `/v1/threads/{id}` | 线程操作 |
| POST/GET | `/v1/threads/{id}/messages` | 添加、列出消息 |
| POST/GET | `/v1/threads/{id}/runs` | 创建、获取执行 |
### RAG / 检索
| Method | Path | 描述 |
|--------|------|------|
| POST | `/v1/rag/index` | 注册文档索引 |
| POST | `/v1/rag` | RAG 搜索与回答生成 |
| POST | `/v1/vector-store/upsert` | 注册向量数据库 |
| POST | `/v1/vector-store/query` | 向量相似度搜索 |
| POST | `/v1/search/searxng` | 注重隐私的 Web 搜索 |
| POST | `/v1/search/web` | Web 搜索 |
### Agent
| Method | Path | 描述 |
|--------|------|------|
| POST | `/v1/agent/run` | 执行 ReAct Agent |
| POST | `/v1/agent/subagent/plan` | 任务分解计划 |
| POST | `/v1/agent/subagent/run` | 执行子 Agent |
| POST | `/v1/agent/tdd/cycle` | TDD 循环(代码生成+测试) |
| POST | `/v1/agent/debug` | 自动调试 |
| POST | `/v1/agent/evolve` | 遗传算法优化 |
### 安全
| Method | Path | 描述 |
|--------|------|------|
| POST | `/v1/security/scan` | Web 应用漏洞扫描 |
| POST | `/v1/security/report/md` | 生成渗透测试报告 |
| POST | `/v1/security/oss/analyze` | OSS 依赖项与漏洞分析 |
| POST | `/v1/security/oss/sbom` | 生成 SBOM (CycloneDX) |
### ML 训练 / 评估
| Method | Path | 描述 |
|--------|------|------|
| POST | `/v1/peft/estimate` | LoRA 内存估算 |
| POST | `/v1/training/simpo/compute-loss` | SimPO 损失计算 |
| POST | `/v1/training/fsdp/estimate` | FSDP 分布式训练估算 |
| POST | `/v1/lm-eval` | LM 基准评估 |
| POST | `/v1/extract` | 结构化信息提取 |
### 多模态
| Method | Path | 描述 |
|--------|------|------|
| POST | `/v1/llava/chat` | 图像+文本理解 |
| POST | `/v1/whisper/transcribe` | 语音转文本 |
| POST | `/v1/diffusion/generate` | 图像生成 |
| POST | `/v1/clip/encode/text` | CLIP 文本 embedding |
### DevOps / 云端
| Method | Path | 描述 |
|--------|------|------|
| POST | `/v1/docker/containers` | Docker 容器列表 |
| POST | `/v1/docker/build` | 构建 Docker 镜像 |
| POST | `/v1/watch/config` | 文件监视配置 |
| POST | `/v1/modal/run` | 执行云函数 (Modal) |
启动后,您可以在 **http://localhost:8000/docs** 查看所有 endpoint 的详细信息。
## 作为 Python 库使用
```
# SEO / LLMO 评分
from open_mythos.llmo import LLMOScorer
scorer = LLMOScorer()
result = scorer.score("""
デジタルマーケティングとは、Google・Meta などのプラットフォームを活用して
顧客を獲得する手法です。2024年の調査では SEO 投資は前年比 32% 増加しています。
""")
print(f"LLMO スコア: {result.llmo_total:.3f}")
print(f"エンティティ密度: {result.entity_density:.3f}")
# 広告ROI計算
from open_mythos.tools_marketing import calculate_roi
roi = calculate_roi(ad_spend=500_000, revenue=1_900_000, cogs=400_000,
clicks=3_800, impressions=120_000)
print(f"ROI: {roi['roi_pct']:+.1f}%")
print(f"ROAS: {roi['roas']:.2f}x")
# Vector Store
from open_mythos.skills.vector_store import VectorStore
vs = VectorStore(dim=384)
vs.upsert("doc1", "重要なドキュメント", {"category": "tech"})
results = vs.query("ドキュメント", top_k=3)
```
## 架构
OpenMythos 实现了 **Recurrent-Depth Transformer (RDT)**。
```
Input
↓
[Prelude P] — 標準Transformerレイヤー (1回実行)
↓
[Recurrent Block R] — T回ループ実行
↑_______↓ h_{t+1} = A·h_t + B·e + Transformer(h_t, e)
↓
[Coda C] — 標準Transformerレイヤー (1回実行)
↓
Output
```
**循环次数 = 推理深度**:增加循环可以实现更深度的推理(推理时缩放)。
### 模型规模
| 变体 | dim | 参数规模 | 推荐用途 |
|-----------|-----|------------|---------|
| `mythos_1b` | 2048 | ~1B | 开发与验证 |
| `mythos_7b` | 3584 | ~7B | 通用任务 |
| `mythos_100b` | 8192 | ~100B | 高精度任务 |
```
from open_mythos import mythos_7b, OpenMythos
cfg = mythos_7b()
model = OpenMythos(cfg)
```
### Attention 实现
| 选项 | 类 | 描述 |
|-----------|--------|------|
| `"gqa"` | `GQAttention` | Grouped Query Attention — 减少 KV 缓存,支持 Flash Attention 2 |
| `"mla"` | `MLAttention` | Multi-Latent Attention (DeepSeek-V2 方式) — 压缩 KV latent |
## 训练
```
# 单 GPU
python training/3b_fine_web_edu.py
# 多 GPU (DDP)
torchrun --nproc_per_node=$(python -c "import torch; print(torch.cuda.device_count())") \
training/3b_fine_web_edu.py
```
| 配置 | 值 |
|------|---|
| 优化器 | AdamW |
| 数据集 | `HuggingFaceFW/fineweb-edu` |
| 精度 | bfloat16 (H100/A100) / float16 + GradScaler |
| 时间表 | Linear warmup (2000 steps) → cosine decay |
## 测试
```
# 全テスト実行
python -m pytest tests/ -q
# 特定スプリントのテスト
python -m pytest tests/test_sprint54.py -v
# カバレッジ確認
python -m pytest tests/ --tb=short -q
```
当前 **2862 个测试 PASS** (Sprint 54 / v0.57.0)
## 目录结构
```
OpenMythos/
├── open_mythos/ # コアライブラリ
│ ├── main.py # RDTモデル本体
│ ├── assistant.py # OpenAI Assistants API互換レイヤー
│ ├── skills/ # スキルプラグイン
│ │ ├── vector_store.py
│ │ ├── agent_framework.py
│ │ ├── security.py
│ │ ├── devops_cloud.py
│ │ └── ...
│ ├── llmo.py # LLMOスコアリング
│ └── tools_marketing.py # マーケティングツール
├── serve/
│ ├── api.py # FastAPI サーバー (127エンドポイント)
│ ├── auth.py # Bearer Token認証 + レートリミット
│ ├── Dockerfile # 本番イメージ
│ └── monitor.py # 精度監視
├── tests/ # テスト (2862 PASS)
├── examples/ # サンプルコード
│ └── api_quickstart.py # API利用サンプル
├── docker-compose.yml # ワンコマンド起動
├── .env.example # 環境変数テンプレート
└── requirements.txt # 依存関係
```
## 环境变量参考
复制 `.env.example` 以创建 `.env`,并设置各个值。
```
cp .env.example .env
```
主要的环境变量:
| 变量 | 默认值 | 描述 |
|------|---------|------|
| `API_KEY` | (无=禁用认证) | Bearer Token 认证密钥 |
| `DEVICE` | `cpu` | `cpu` 或 `cuda` |
| `DEFAULT_LOOPS` | `4` | 默认循环次数 |
| `RATE_LIMIT_RPM` | `60` | 每分钟请求限制 |
| `WORKERS` | `2` | Gunicorn worker 数量 |
| `MODEL_CHECKPOINT` | (无) | 训练完成的 checkpoint 路径 |
详情请参阅 [`.env.example`](.env.example)。
## 部署到 Cloud Run
```
cp serve/cloudrun.env.example serve/cloudrun.env
# serve/cloudrun.env を編集して GCP プロジェクト ID 等を設定
bash serve/deploy_cloudrun.sh
```
## 理论背景
OpenMythos 设想的“Claude Mythos”架构是 **Recurrent-Depth Transformer (RDT)**。普通的 Transformer 通过堆叠层来构建,而 RDT 会多次重复使用部分层。
- **循环次数 = 推理深度**:只需在推理时增加循环即可实现深度推理
- **LTI 稳定性**:通过将注入参数约束为 `ρ(A) < 1` 来保证训练稳定性
- **Scaling Law**:存在同时缩放循环次数和 token 数量的最佳法则
- **MoE 扩展**:通过用 Mixture-of-Experts 替换 FFN 来存储广泛的知识
详情请参阅 [`docs/open_mythos.md`](docs/open_mythos.md)。
## 许可证
MIT License — Copyright (c) 2026 Kye Gomez
## 参考文献
- [Loop, Think, & Generalize — Implicit Reasoning in Recurrent Depth Transformers](https://arxiv.org/pdf/2604.07822)
- [Parcae — Scaling Laws for Stable Looped Language Models](https://arxiv.org/abs/2604.12946)
- [Reasoning with Latent Thoughts — On the Power of Looped Transformers](https://arxiv.org/abs/2502.17416)
- [Relaxed Recursive Transformers — Effective Parameter Sharing with Layer-wise LoRA](https://arxiv.org/pdf/2410.20672)
标签:AI服务器, CISA项目, DLL 劫持, OpenAI兼容, RAG, REST API, 凭据扫描, 多模态, 大语言模型, 安全测试, 攻击性安全, 请求拦截, 逆向工具