kofdai commited on
Commit
0e993ea
·
verified ·
1 Parent(s): 3f9e2e3

Upload DEVELOPER_GUIDE.md with huggingface_hub

Browse files
Files changed (1) hide show
  1. DEVELOPER_GUIDE.md +1286 -0
DEVELOPER_GUIDE.md ADDED
@@ -0,0 +1,1286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # NULL AI プロジェクト - 開発者向け技術ガイド
2
+
3
+ ## 📋 目次
4
+
5
+ 1. [プロジェクト概要](#プロジェクト概要)
6
+ 2. [システムアーキテクチャ](#システムアーキテクチャ)
7
+ 3. [ディレクトリ構造](#ディレクトリ構造)
8
+ 4. [技術スタック](#技術スタック)
9
+ 5. [データベース設計](#データベース設計)
10
+ 6. [API仕様](#api仕様)
11
+ 7. [フロントエンド構成](#フロントエンド構成)
12
+ 8. [バックエンド構成](#バックエンド構成)
13
+ 9. [推論エンジン](#推論エンジン)
14
+ 10. [開発環境セットアップ](#開発環境セットアップ)
15
+ 11. [デプロイメント](#デプロイメント)
16
+ 12. [トラブルシューティング](#トラブルシューティング)
17
+
18
+ ---
19
+
20
+ ## プロジェクト概要
21
+
22
+ ### プロジェクト名
23
+ **NULL AI** - ドメイン特化型AI推論システム
24
+
25
+ ### 目的
26
+ 医療・法律など特定ドメインに特化した、高精度なAI質問応答システムを提供する。
27
+
28
+ ### 主な機能
29
+ - **ドメイン特化型推論**: 医療(medical)、法律(legal)、一般(general)の3つのドメインに対応
30
+ - **多段階判定システム**: Judge Alpha → Judge Beta Basic → Judge Beta Advanced の3段階評価
31
+ - **知識ベース拡張**: IATH (Indexed Athens) 形式での知識タイル管理
32
+ - **リアルタイムストリーミング**: WebSocketによるトークンレベルのリアルタイム配信
33
+ - **キャッシュ機構**: 頻繁なクエリの高速化
34
+ - **ユーザー認証**: JWT based認証システム
35
+
36
+ ---
37
+
38
+ ## システムアーキテクチャ
39
+
40
+ ### 全体構成図
41
+
42
+ ```
43
+ ┌─────────────────────────────────────────────────────────┐
44
+ │ クライアント層 │
45
+ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
46
+ │ │ React UI │ │ HF Space UI │ │ REST Client │ │
47
+ │ └──────────────┘ └──────────────┘ └──────────────┘ │
48
+ └─────────────────────────────────────────────────────────┘
49
+
50
+
51
+ ┌─────────────────────────────────────────────────────────┐
52
+ │ API Gateway層 │
53
+ │ ┌──────────────────────────────────────────────────┐ │
54
+ │ │ FastAPI Server (port 8000) │ │
55
+ │ │ - REST API Endpoints │ │
56
+ │ │ - WebSocket Endpoints │ │
57
+ │ │ - JWT Authentication Middleware │ │
58
+ │ └──────────────────────────────────────────────────┘ │
59
+ └─────────────────────────────────────────────────────────┘
60
+
61
+
62
+ ┌─────────────────────────────────────────────────────────┐
63
+ │ サービス層 │
64
+ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
65
+ │ │ Inference │ │ Cache │ │ Auth │ │
66
+ │ │ Service │ │ Service │ │ Service │ │
67
+ │ └──────────────┘ └──────────────┘ └──────────────┘ │
68
+ └─────────────────────────────────────────────────────────┘
69
+
70
+
71
+ ┌─────────────────────────────────────────────────────────┐
72
+ │ 推論エンジン層 │
73
+ │ ┌──────────────────────────────────────────────────┐ │
74
+ │ │ Inference Engine Unified │ │
75
+ │ │ │ │
76
+ │ │ ┌────────────┐ ┌────────────┐ ┌────────────┐ │ │
77
+ │ │ │Judge Alpha │→│Judge Beta │→│Judge Beta │ │ │
78
+ │ │ │ Lobe │ │Basic Lobe │ │Advanced │ │ │
79
+ │ │ └────────────┘ └────────────┘ └────────────┘ │ │
80
+ │ │ │ │
81
+ │ │ ┌────────────────────────────────────────────┐ │ │
82
+ │ │ │ Knowledge Tile Generator │ │ │
83
+ │ │ └────────────────────────────────────────────┘ │ │
84
+ │ └──────────────────────────────────────────────────┘ │
85
+ └─────────────────────────────────────────────────────────┘
86
+
87
+
88
+ ┌─────────────────────────────────────────────────────────┐
89
+ │ データ層 │
90
+ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
91
+ │ │ PostgreSQL │ │ IATH DB │ │ Hot Cache │ │
92
+ │ │ (Users, │ │ (Knowledge │ │ (Redis-like)│ │
93
+ │ │ Sessions) │ │ Tiles) │ │ │ │
94
+ │ └──────────────┘ └──────────────┘ └──────────────┘ │
95
+ └─────────────────────────────────────────────────────────┘
96
+
97
+
98
+ ┌─────────────────────────────────────────────────────────┐
99
+ │ AI モデル層 │
100
+ │ ┌──────────────────────────────────────────────────┐ │
101
+ │ │ Model Router (Hugging Face Integration) │ │
102
+ │ │ │ │
103
+ │ │ - DeepSeek-R1-Distill-Qwen-32B (医療・法律) │ │
104
+ │ │ - Qwen2.5-7B-Instruct (一般) │ │
105
+ │ │ - その他カスタムモデル │ │
106
+ │ └──────────────────────────────────────────────────┘ │
107
+ └─────────────────────────────────────────────────────────┘
108
+ ```
109
+
110
+ ### データフロー
111
+
112
+ #### 1. ユーザークエリの処理フロー
113
+
114
+ ```
115
+ User Question
116
+
117
+
118
+ [Frontend] Send POST /api/questions or WebSocket
119
+
120
+
121
+ [API Gateway] Route to appropriate endpoint
122
+
123
+ ├─ JWT Token Validation
124
+
125
+
126
+ [InferenceService] process_question()
127
+
128
+ ├─ Check Hot Cache
129
+ │ └─ Cache Hit? → Return cached response
130
+
131
+
132
+ [Judge Alpha Lobe] 初期判定
133
+
134
+ ├─ 質問の複雑度評価 (complexity: 0.0-1.0)
135
+ ├─ ドメイン適合性評価 (domain_fit: 0.0-1.0)
136
+ └─ 処理フロー決定
137
+
138
+
139
+ ┌───────────────────────────┐
140
+ │ complexity < 0.3? │
141
+ └───────────────────────────┘
142
+ │ │
143
+ │Yes │No
144
+ ▼ ▼
145
+ [Judge Beta Basic] [Judge Beta Advanced]
146
+ │ │
147
+ ├─ 軽量推論 ├─ 知識ベース検索
148
+ └─ 高速応答 ├─ コンテキスト拡張
149
+ └─ 高精度推論
150
+
151
+
152
+ [Model Router] モデル選択・推論実行
153
+
154
+ ├─ ドメイン特化モデル選択
155
+ ├─ プロンプトテンプレート適用
156
+ └─ ストリーミング生成
157
+
158
+
159
+ [Response Post-Processing]
160
+
161
+ ├─ 幻覚検出 (Hallucination Detection)
162
+ ├─ 確信度計算 (Confidence Scoring)
163
+ └─ メタデータ付与
164
+
165
+
166
+ [Cache Update] Hot Cache更新
167
+
168
+
169
+ [Response] クライアントへ返却
170
+ ```
171
+
172
+ ---
173
+
174
+ ## ディレクトリ構造
175
+
176
+ ```
177
+ project_locate/
178
+
179
+ ├── frontend/ # React フロントエンド
180
+ │ ├── src/
181
+ │ │ ├── components/ # UI コンポーネント
182
+ │ │ │ ├── ChatInterface.tsx # チャットUI
183
+ │ │ │ ├── LoginForm.tsx # ログインフォーム
184
+ │ │ │ └── ThinkingIndicator.tsx # 思考プロセス表示
185
+ │ │ ├── services/ # API クライアント
186
+ │ │ │ ├── api.ts # REST API
187
+ │ │ │ └── websocket.ts # WebSocket
188
+ │ │ ├── hooks/ # Reactフック
189
+ │ │ ├── App.tsx # アプリケーションルート
190
+ │ │ └── index.tsx # エントリーポイント
191
+ │ ├── public/
192
+ │ └── package.json
193
+
194
+ ├── backend/ # FastAPI バックエンド
195
+ │ ├── app/
196
+ │ │ ├── api/ # APIルート
197
+ │ │ │ ├── auth.py # 認証エンドポイント
198
+ │ │ │ ├── questions.py # 質問処理エンドポイント
199
+ │ │ │ └── health.py # ヘルスチェック
200
+ │ │ ├── models/ # データモデル
201
+ │ │ │ ├── user.py # ユーザーモデル
202
+ │ │ │ └── session.py # セッションモデル
203
+ │ │ ├── services/ # ビジネスロジック
204
+ │ │ │ ├── inference_service.py # 推論サービス
205
+ │ │ │ └── cache_service.py # キャッシュサービス
206
+ │ │ ├── middleware/ # ミドルウェア
207
+ │ │ │ └── auth.py # JWT認証
208
+ │ │ ├── utils/ # ユーティリティ
209
+ │ │ │ ├── password_hash.py # パスワードハッシュ化
210
+ │ │ │ └── jwt_handler.py # JWT処理
211
+ │ │ └── main.py # FastAPIアプリケーション
212
+ │ └── requirements.txt
213
+
214
+ ├── null_ai/ # 推論エンジンコア
215
+ │ ├── inference_engine_unified.py # 統合推論エンジン
216
+ │ ├── judge_alpha_lobe.py # Judge Alpha (初期判定)
217
+ │ ├── judge_beta_lobe_basic.py # Judge Beta Basic (軽量推論)
218
+ │ ├── judge_beta_lobe_advanced.py # Judge Beta Advanced (高精度推論)
219
+ │ ├── knowledge_tile_generator.py # 知識タイル生成
220
+ │ ├── hallucination_detector.py # 幻覚検出
221
+ │ ├── model_router.py # モデル選択・ルーティング
222
+ │ ├── iath_encoder.py # IATH エンコーダー
223
+ │ ├── iath_decoder.py # IATH デコーダー
224
+ │ ├── hot_cache.py # ホットキャッシュ
225
+ │ └── db_manager.py # データベース管理
226
+
227
+ ├── ilm_athens_engine/ # IATH システム
228
+ │ ├── layer1_spatial_encoding.py # 空間エンコーディング
229
+ │ ├── layer2_episodic_binding.py # エピソード結合
230
+ │ └── layer5_state_management.py # 状態管理
231
+
232
+ ├── documentation/ # ドキュメント
233
+ │ ├── API_REFERENCE.md # API仕様書
234
+ │ ├── ARCHITECTURE.md # アーキテクチャ設計
235
+ │ └── DEPLOYMENT.md # デプロイ手順
236
+
237
+ ├── docker-compose.yml # Docker構成
238
+ ├── start_null_ai.sh # 起動スクリプト
239
+ ├── requirements.txt # Pythonパッケージ
240
+ └── README.md # プロジェクト概要
241
+ ```
242
+
243
+ ---
244
+
245
+ ## 技術スタック
246
+
247
+ ### フロントエンド
248
+
249
+ | 技術 | バージョン | 用途 |
250
+ |------|-----------|------|
251
+ | **React** | 18.x | UIフレームワーク |
252
+ | **TypeScript** | 5.x | 型安全性 |
253
+ | **Vite** | 4.x | ビルドツール |
254
+ | **Axios** | 1.x | HTTP クライアント |
255
+ | **WebSocket API** | - | リアルタイム通信 |
256
+ | **Tailwind CSS** | 3.x | スタイリング |
257
+
258
+ ### バックエンド
259
+
260
+ | 技術 | バージョン | 用途 |
261
+ |------|-----------|------|
262
+ | **FastAPI** | 0.104+ | Web フレームワーク |
263
+ | **Python** | 3.10+ | プログラミング言語 |
264
+ | **Uvicorn** | 0.24+ | ASGI サーバー |
265
+ | **PostgreSQL** | 14+ | リレーショナルDB |
266
+ | **SQLAlchemy** | 2.x | ORM |
267
+ | **Pydantic** | 2.x | データバリデーション |
268
+ | **JWT** | - | 認証トークン |
269
+ | **Passlib** | 1.7+ | パスワードハッシュ化 |
270
+
271
+ ### AI/ML
272
+
273
+ | 技術 | バージョン | 用途 |
274
+ |------|-----------|------|
275
+ | **Transformers** | 4.36+ | HuggingFace モデル |
276
+ | **PyTorch** | 2.1+ | 深層学習フレームワーク |
277
+ | **DeepSeek-R1** | 32B distill | 医療・法律推論 |
278
+ | **Qwen2.5** | 7B | 一般推論 |
279
+ | **Accelerate** | 0.25+ | 分散処理 |
280
+ | **CUDA** | 11.8+ | GPU アクセラレーション |
281
+
282
+ ### インフラ
283
+
284
+ | 技術 | 用途 |
285
+ |------|------|
286
+ | **Docker** | コンテナ化 |
287
+ | **HuggingFace Spaces** | デモデプロイ |
288
+ | **Nginx** | リバースプロキシ |
289
+ | **Git** | バージョン管理 |
290
+
291
+ ---
292
+
293
+ ## データベース設計
294
+
295
+ ### PostgreSQL スキーマ
296
+
297
+ #### users テーブル
298
+ ```sql
299
+ CREATE TABLE users (
300
+ id SERIAL PRIMARY KEY,
301
+ email VARCHAR(255) UNIQUE NOT NULL,
302
+ username VARCHAR(100) UNIQUE NOT NULL,
303
+ hashed_password VARCHAR(255) NOT NULL,
304
+ is_active BOOLEAN DEFAULT TRUE,
305
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
306
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
307
+ );
308
+
309
+ CREATE INDEX idx_users_email ON users(email);
310
+ CREATE INDEX idx_users_username ON users(username);
311
+ ```
312
+
313
+ #### sessions テーブル
314
+ ```sql
315
+ CREATE TABLE sessions (
316
+ id SERIAL PRIMARY KEY,
317
+ session_id VARCHAR(255) UNIQUE NOT NULL,
318
+ user_id INTEGER REFERENCES users(id),
319
+ domain_id VARCHAR(50) NOT NULL,
320
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
321
+ last_activity TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
322
+ metadata JSONB
323
+ );
324
+
325
+ CREATE INDEX idx_sessions_user_id ON sessions(user_id);
326
+ CREATE INDEX idx_sessions_session_id ON sessions(session_id);
327
+ ```
328
+
329
+ #### conversation_history テーブル
330
+ ```sql
331
+ CREATE TABLE conversation_history (
332
+ id SERIAL PRIMARY KEY,
333
+ session_id VARCHAR(255) REFERENCES sessions(session_id),
334
+ question TEXT NOT NULL,
335
+ response TEXT NOT NULL,
336
+ confidence FLOAT,
337
+ model_used VARCHAR(255),
338
+ thinking_process JSONB,
339
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
340
+ );
341
+
342
+ CREATE INDEX idx_conv_history_session_id ON conversation_history(session_id);
343
+ ```
344
+
345
+ ### IATH データベース構造
346
+
347
+ IATH (Indexed Athens) データベースは独自のバイナリ形式で保存されます。
348
+
349
+ ```
350
+ ilm_athens_medical_db.iath
351
+ ├── Header Section
352
+ │ ├── Version: 1.0
353
+ │ ├── Domain: medical
354
+ │ └── Tile Count: N
355
+
356
+ ├── Tile Index
357
+ │ └── [tile_id → offset mapping]
358
+
359
+ └── Tile Data Sections
360
+ └── Each Tile:
361
+ ├── tile_id (UUID)
362
+ ├── topic (string)
363
+ ├── coordinates (3D vector)
364
+ ├── content (text)
365
+ ├── metadata (JSON)
366
+ └── timestamp
367
+ ```
368
+
369
+ ---
370
+
371
+ ## API仕様
372
+
373
+ ### ベースURL
374
+ ```
375
+ http://localhost:8000/api
376
+ ```
377
+
378
+ ### 認証
379
+
380
+ #### POST /auth/register
381
+ 新規ユーザー登録
382
+
383
+ **リクエスト**
384
+ ```json
385
+ {
386
+ "email": "user@example.com",
387
+ "username": "username",
388
+ "password": "secure_password"
389
+ }
390
+ ```
391
+
392
+ **レスポンス**
393
+ ```json
394
+ {
395
+ "id": 1,
396
+ "email": "user@example.com",
397
+ "username": "username",
398
+ "created_at": "2025-01-01T00:00:00Z"
399
+ }
400
+ ```
401
+
402
+ #### POST /auth/login
403
+ ログイン
404
+
405
+ **リクエスト**
406
+ ```json
407
+ {
408
+ "username": "username",
409
+ "password": "secure_password"
410
+ }
411
+ ```
412
+
413
+ **レスポンス**
414
+ ```json
415
+ {
416
+ "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
417
+ "token_type": "bearer",
418
+ "user": {
419
+ "id": 1,
420
+ "username": "username",
421
+ "email": "user@example.com"
422
+ }
423
+ }
424
+ ```
425
+
426
+ ### 質問処理
427
+
428
+ #### POST /questions/
429
+ 質問を送信(非ストリーミング)
430
+
431
+ **リクエスト**
432
+ ```json
433
+ {
434
+ "question": "心筋梗塞の初期症状は?",
435
+ "session_id": "sess_123",
436
+ "domain_id": "medical",
437
+ "model_id": "deepseek-r1-32b",
438
+ "stream": false
439
+ }
440
+ ```
441
+
442
+ **レスポンス**
443
+ ```json
444
+ {
445
+ "session_id": "sess_123",
446
+ "question": "心筋梗塞の初期症状は?",
447
+ "response": "心筋梗塞の初期症状には...",
448
+ "status": "success",
449
+ "confidence": 0.92,
450
+ "memory_augmented": true,
451
+ "thinking": "Judge Alpha: complexity=0.7, Judge Beta Advanced selected...",
452
+ "model_used": "deepseek-r1-32b"
453
+ }
454
+ ```
455
+
456
+ #### WebSocket /questions/ws/{session_id}
457
+ リアルタイムストリーミング
458
+
459
+ **接続**
460
+ ```javascript
461
+ const ws = new WebSocket('ws://localhost:8000/api/questions/ws/sess_123');
462
+ ```
463
+
464
+ **送信メッセージ**
465
+ ```json
466
+ {
467
+ "type": "question",
468
+ "question": "糖尿病の予防方法は?",
469
+ "domain_id": "medical",
470
+ "model_id": "deepseek-r1-32b",
471
+ "stream": true
472
+ }
473
+ ```
474
+
475
+ **受信メッセージ (ストリーミング)**
476
+ ```json
477
+ // 接続確認
478
+ {"type": "connected", "session_id": "sess_123", "message": "WebSocket connected"}
479
+
480
+ // 処理開始
481
+ {"type": "processing", "message": "Processing your question..."}
482
+
483
+ // 思考プロセス
484
+ {"type": "thinking", "step": "Judge Alpha evaluating..."}
485
+
486
+ // トークンストリーム
487
+ {"type": "token", "content": "糖尿病"}
488
+ {"type": "token", "content": "の"}
489
+ {"type": "token", "content": "予防"}
490
+ ...
491
+
492
+ // 完了
493
+ {
494
+ "type": "response",
495
+ "session_id": "sess_123",
496
+ "question": "糖尿病の予防方法は?",
497
+ "response": "糖尿病の予防には...",
498
+ "status": "success"
499
+ }
500
+ ```
501
+
502
+ #### GET /health
503
+ ヘルスチェック
504
+
505
+ **レスポンス**
506
+ ```json
507
+ {
508
+ "status": "healthy",
509
+ "version": "1.0.0",
510
+ "timestamp": "2025-01-01T00:00:00Z"
511
+ }
512
+ ```
513
+
514
+ ---
515
+
516
+ ## フロントエンド構成
517
+
518
+ ### コンポーネント階層
519
+
520
+ ```
521
+ App
522
+ ├── AuthProvider
523
+ │ ├── LoginForm
524
+ │ └── RegisterForm
525
+
526
+ ├── ChatInterface
527
+ │ ├── MessageList
528
+ │ │ ├── UserMessage
529
+ │ │ └── AIMessage
530
+ │ │ └── ThinkingIndicator
531
+ │ ├── InputArea
532
+ │ └── DomainSelector
533
+
534
+ └── SettingsPanel
535
+ ├── ModelSelector
536
+ └── ThemeToggle
537
+ ```
538
+
539
+ ### 主要コンポーネント
540
+
541
+ #### ChatInterface.tsx
542
+ ```typescript
543
+ interface ChatInterfaceProps {
544
+ sessionId: string;
545
+ domain: 'medical' | 'legal' | 'general';
546
+ }
547
+
548
+ const ChatInterface: React.FC<ChatInterfaceProps> = ({ sessionId, domain }) => {
549
+ const [messages, setMessages] = useState<Message[]>([]);
550
+ const [isThinking, setIsThinking] = useState(false);
551
+ const ws = useRef<WebSocket | null>(null);
552
+
553
+ useEffect(() => {
554
+ // WebSocket接続
555
+ ws.current = new WebSocket(`ws://localhost:8000/api/questions/ws/${sessionId}`);
556
+
557
+ ws.current.onmessage = (event) => {
558
+ const data = JSON.parse(event.data);
559
+ handleWebSocketMessage(data);
560
+ };
561
+
562
+ return () => ws.current?.close();
563
+ }, [sessionId]);
564
+
565
+ const sendQuestion = (question: string) => {
566
+ ws.current?.send(JSON.stringify({
567
+ type: 'question',
568
+ question,
569
+ domain_id: domain,
570
+ stream: true
571
+ }));
572
+ };
573
+
574
+ // ...
575
+ };
576
+ ```
577
+
578
+ ### 状態管理
579
+
580
+ Redux/Context API を使用した状態管理:
581
+
582
+ ```typescript
583
+ interface AppState {
584
+ auth: {
585
+ user: User | null;
586
+ token: string | null;
587
+ isAuthenticated: boolean;
588
+ };
589
+ chat: {
590
+ sessions: Record<string, Session>;
591
+ currentSessionId: string | null;
592
+ messages: Message[];
593
+ };
594
+ settings: {
595
+ domain: DomainType;
596
+ model: string;
597
+ theme: 'light' | 'dark';
598
+ };
599
+ }
600
+ ```
601
+
602
+ ---
603
+
604
+ ## バックエンド構成
605
+
606
+ ### FastAPI アプリケーション構造
607
+
608
+ #### backend/app/main.py
609
+ ```python
610
+ from fastapi import FastAPI
611
+ from fastapi.middleware.cors import CORSMiddleware
612
+ from backend.app.api import auth, questions, health
613
+ from backend.app.middleware.auth import JWTMiddleware
614
+
615
+ app = FastAPI(
616
+ title="NULL AI API",
617
+ version="1.0.0",
618
+ description="Domain-specific AI inference system"
619
+ )
620
+
621
+ # CORS設定
622
+ app.add_middleware(
623
+ CORSMiddleware,
624
+ allow_origins=["http://localhost:3000"],
625
+ allow_credentials=True,
626
+ allow_methods=["*"],
627
+ allow_headers=["*"],
628
+ )
629
+
630
+ # ルート登録
631
+ app.include_router(auth.router, prefix="/api/auth", tags=["auth"])
632
+ app.include_router(questions.router, prefix="/api/questions", tags=["questions"])
633
+ app.include_router(health.router, prefix="/api", tags=["health"])
634
+
635
+ @app.on_event("startup")
636
+ async def startup_event():
637
+ """アプリケーション起動時の初期化"""
638
+ # データベース接続
639
+ # キャッシュ初期化
640
+ # モデルプリロード
641
+ pass
642
+
643
+ @app.on_event("shutdown")
644
+ async def shutdown_event():
645
+ """アプリケーション終了時のクリーンアップ"""
646
+ pass
647
+ ```
648
+
649
+ ### 依存性注入
650
+
651
+ ```python
652
+ from typing import Generator
653
+ from fastapi import Depends
654
+ from sqlalchemy.orm import Session
655
+ from backend.app.database import SessionLocal
656
+
657
+ def get_db() -> Generator:
658
+ """データベースセッション取得"""
659
+ db = SessionLocal()
660
+ try:
661
+ yield db
662
+ finally:
663
+ db.close()
664
+
665
+ def get_current_user(
666
+ token: str = Depends(oauth2_scheme),
667
+ db: Session = Depends(get_db)
668
+ ) -> User:
669
+ """現在のユーザー取得"""
670
+ payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
671
+ user_id = payload.get("sub")
672
+ user = db.query(User).filter(User.id == user_id).first()
673
+ if not user:
674
+ raise HTTPException(status_code=401, detail="Invalid token")
675
+ return user
676
+ ```
677
+
678
+ ---
679
+
680
+ ## 推論エンジン
681
+
682
+ ### Judge Alpha Lobe (初期判定)
683
+
684
+ **役割**: 質問の複雑度とドメイン適合性を評価し、適切な処理フローを決定
685
+
686
+ **実装**: `null_ai/judge_alpha_lobe.py`
687
+
688
+ ```python
689
+ class JudgeAlphaLobe:
690
+ def evaluate(self, question: str, domain: str) -> dict:
691
+ """
692
+ 質問を評価し、処理フローを決定
693
+
694
+ Returns:
695
+ {
696
+ "complexity": float (0.0-1.0),
697
+ "domain_fit": float (0.0-1.0),
698
+ "recommended_judge": "beta_basic" | "beta_advanced",
699
+ "reasoning": str
700
+ }
701
+ """
702
+ # 質問の長さ、専門用語密度、構造複雑度を分析
703
+ complexity = self._calculate_complexity(question)
704
+ domain_fit = self._evaluate_domain_fit(question, domain)
705
+
706
+ if complexity < 0.3:
707
+ recommended_judge = "beta_basic"
708
+ else:
709
+ recommended_judge = "beta_advanced"
710
+
711
+ return {
712
+ "complexity": complexity,
713
+ "domain_fit": domain_fit,
714
+ "recommended_judge": recommended_judge,
715
+ "reasoning": self._generate_reasoning(complexity, domain_fit)
716
+ }
717
+ ```
718
+
719
+ ### Judge Beta Basic (軽量推論)
720
+
721
+ **役割**: 低複雑度の質問に対して高速に応答
722
+
723
+ **特徴**:
724
+ - 知識ベース検索なし
725
+ - 小型モデル使用 (Qwen2.5-7B)
726
+ - 低レイテンシ (<2秒)
727
+
728
+ ### Judge Beta Advanced (高精度推論)
729
+
730
+ **役割**: 高複雑度の質問に対して知識ベース拡張した高精度応答
731
+
732
+ **特徴**:
733
+ - IATH知識ベース検索
734
+ - 大型モデル使用 (DeepSeek-R1-32B)
735
+ - コンテキスト拡張 (最大4096トークン)
736
+ - 幻覚検出機構
737
+
738
+ **実装フロー**:
739
+ ```python
740
+ class JudgeBetaAdvanced:
741
+ async def process(self, question: str, domain: str, context: dict) -> dict:
742
+ # 1. 知識ベース検索
743
+ relevant_tiles = await self.search_knowledge_base(question, domain)
744
+
745
+ # 2. コンテキスト構築
746
+ augmented_context = self.build_context(question, relevant_tiles, context)
747
+
748
+ # 3. プロンプト生成
749
+ prompt = self.generate_prompt(question, augmented_context, domain)
750
+
751
+ # 4. モデル推論
752
+ response = await self.model_router.generate(
753
+ prompt=prompt,
754
+ model_id=self.select_model(domain),
755
+ max_tokens=2048,
756
+ temperature=0.7
757
+ )
758
+
759
+ # 5. 幻覚検出
760
+ is_hallucinated = self.hallucination_detector.detect(response, relevant_tiles)
761
+
762
+ # 6. 確信度計算
763
+ confidence = self.calculate_confidence(response, relevant_tiles)
764
+
765
+ return {
766
+ "answer": response,
767
+ "confidence": confidence,
768
+ "hallucination_detected": is_hallucinated,
769
+ "sources": [tile.id for tile in relevant_tiles],
770
+ "reasoning": self.extract_reasoning(response)
771
+ }
772
+ ```
773
+
774
+ ### Knowledge Tile Generator
775
+
776
+ **役割**: ドメイン知識を構造化されたタイル形式で生成・管理
777
+
778
+ **タイル構造**:
779
+ ```python
780
+ @dataclass
781
+ class KnowledgeTile:
782
+ tile_id: str # UUID
783
+ topic: str # トピック
784
+ coordinates: tuple[float, float, float] # 3D空間座標
785
+ content: str # 知識コンテンツ
786
+ domain: str # ドメイン
787
+ confidence: float # 確信度
788
+ metadata: dict # メタデータ
789
+ created_at: datetime
790
+ updated_at: datetime
791
+ ```
792
+
793
+ ---
794
+
795
+ ## 開発環境セットアップ
796
+
797
+ ### 必要環境
798
+
799
+ - **OS**: macOS / Linux / Windows (WSL2)
800
+ - **Python**: 3.10 以上
801
+ - **Node.js**: 18 以上
802
+ - **PostgreSQL**: 14 以上
803
+ - **GPU**: NVIDIA (CUDA 11.8+) 推奨
804
+ - **メモリ**: 32GB以上推奨 (DeepSeek-R1-32B使用時)
805
+
806
+ ### セットアップ手順
807
+
808
+ #### 1. リポジトリクローン
809
+ ```bash
810
+ git clone <repository-url>
811
+ cd project_locate
812
+ ```
813
+
814
+ #### 2. Python環境構築
815
+ ```bash
816
+ # 仮想環境作成
817
+ python -m venv venv
818
+ source venv/bin/activate # Windows: venv\Scripts\activate
819
+
820
+ # 依存関係インストール
821
+ pip install -r requirements.txt
822
+ ```
823
+
824
+ #### 3. データベースセットアップ
825
+ ```bash
826
+ # PostgreSQL起動
827
+ brew services start postgresql # macOS
828
+ # または
829
+ sudo systemctl start postgresql # Linux
830
+
831
+ # データベース作成
832
+ createdb nullai_db
833
+
834
+ # マイグレーション実行
835
+ alembic upgrade head
836
+ ```
837
+
838
+ #### 4. 環境変数設定
839
+ `.env` ファイルを作成:
840
+ ```bash
841
+ # データベース
842
+ DATABASE_URL=postgresql://user:password@localhost/nullai_db
843
+
844
+ # JWT認証
845
+ SECRET_KEY=your-secret-key-here
846
+ ALGORITHM=HS256
847
+ ACCESS_TOKEN_EXPIRE_MINUTES=30
848
+
849
+ # HuggingFace
850
+ HF_TOKEN=your-huggingface-token
851
+
852
+ # モデル設定
853
+ DEFAULT_MODEL=deepseek-r1-32b
854
+ MODEL_CACHE_DIR=./model_cache
855
+ ```
856
+
857
+ #### 5. フロントエンドセットアップ
858
+ ```bash
859
+ cd frontend
860
+ npm install
861
+ ```
862
+
863
+ #### 6. 起動
864
+
865
+ **バックエンド起動**
866
+ ```bash
867
+ ./start_null_ai.sh backend
868
+ # または
869
+ cd backend && uvicorn app.main:app --reload --port 8000
870
+ ```
871
+
872
+ **フロントエンド起動**
873
+ ```bash
874
+ cd frontend && npm run dev
875
+ ```
876
+
877
+ **アクセス**
878
+ - フロントエンド: http://localhost:3000
879
+ - バックエンドAPI: http://localhost:8000
880
+ - API ドキュメント: http://localhost:8000/docs
881
+
882
+ ---
883
+
884
+ ## デプロイメント
885
+
886
+ ### Docker デプロイ
887
+
888
+ #### docker-compose.yml
889
+ ```yaml
890
+ version: '3.8'
891
+
892
+ services:
893
+ backend:
894
+ build: ./backend
895
+ ports:
896
+ - "8000:8000"
897
+ environment:
898
+ - DATABASE_URL=postgresql://postgres:password@db:5432/nullai
899
+ - SECRET_KEY=${SECRET_KEY}
900
+ depends_on:
901
+ - db
902
+ volumes:
903
+ - ./model_cache:/app/model_cache
904
+
905
+ frontend:
906
+ build: ./frontend
907
+ ports:
908
+ - "3000:3000"
909
+ depends_on:
910
+ - backend
911
+
912
+ db:
913
+ image: postgres:14
914
+ environment:
915
+ - POSTGRES_DB=nullai
916
+ - POSTGRES_PASSWORD=password
917
+ volumes:
918
+ - postgres_data:/var/lib/postgresql/data
919
+
920
+ volumes:
921
+ postgres_data:
922
+ ```
923
+
924
+ #### デプロイコマンド
925
+ ```bash
926
+ # ビルド
927
+ docker-compose build
928
+
929
+ # 起動
930
+ docker-compose up -d
931
+
932
+ # ログ確認
933
+ docker-compose logs -f
934
+
935
+ # 停止
936
+ docker-compose down
937
+ ```
938
+
939
+ ### HuggingFace Spaces デプロイ
940
+
941
+ #### requirements.txt (Space用)
942
+ ```txt
943
+ gradio==4.44.0
944
+ huggingface_hub==0.19.4
945
+ transformers==4.36.0
946
+ torch==2.1.0
947
+ accelerate==0.25.0
948
+ ```
949
+
950
+ #### app.py (Space用)
951
+ ```python
952
+ import gradio as gr
953
+ from null_ai.inference_engine_unified import InferenceEngine
954
+
955
+ engine = InferenceEngine()
956
+
957
+ def chat(message, history, domain):
958
+ response = engine.process_question(
959
+ question=message,
960
+ domain_id=domain,
961
+ user_id="space_user"
962
+ )
963
+ return response["answer"]
964
+
965
+ iface = gr.ChatInterface(
966
+ fn=chat,
967
+ additional_inputs=[
968
+ gr.Dropdown(["medical", "legal", "general"], label="Domain")
969
+ ],
970
+ title="NULL AI - Domain-Specific AI Assistant"
971
+ )
972
+
973
+ iface.launch()
974
+ ```
975
+
976
+ #### アップロード
977
+ ```bash
978
+ huggingface-cli upload kofdai/null-ai . --repo-type space
979
+ ```
980
+
981
+ ---
982
+
983
+ ## トラブルシューティング
984
+
985
+ ### 1. Port Already in Use (ポート競合)
986
+
987
+ **症状**: `Address already in use` エラー
988
+
989
+ **解決方法**:
990
+ ```bash
991
+ # ポート8000を使用しているプロセスを確認
992
+ lsof -i :8000
993
+
994
+ # プロセスを終了
995
+ kill -9 <PID>
996
+
997
+ # または停止スクリプト使用
998
+ ./start_null_ai.sh stop
999
+ ```
1000
+
1001
+ ### 2. Model Loading Error (モデル読み込みエラー)
1002
+
1003
+ **症状**: `OutOfMemoryError` または `Model not found`
1004
+
1005
+ **解決方法**:
1006
+ ```bash
1007
+ # 1. メモリ不足の場合: 軽量モデルに切り替え
1008
+ export DEFAULT_MODEL=qwen2-7b
1009
+
1010
+ # 2. モデルキャッシュクリア
1011
+ rm -rf ~/.cache/huggingface/
1012
+
1013
+ # 3. モデル再ダウンロード
1014
+ python -c "from transformers import AutoModelForCausalLM; AutoModelForCausalLM.from_pretrained('deepseek-ai/DeepSeek-R1-Distill-Qwen-32B')"
1015
+ ```
1016
+
1017
+ ### 3. Database Connection Error
1018
+
1019
+ **症状**: `Connection refused` または `Database does not exist`
1020
+
1021
+ **解決方法**:
1022
+ ```bash
1023
+ # PostgreSQL起動確認
1024
+ brew services list # macOS
1025
+ systemctl status postgresql # Linux
1026
+
1027
+ # データベース存在確認
1028
+ psql -l
1029
+
1030
+ # データベース作成
1031
+ createdb nullai_db
1032
+
1033
+ # マイグレーション実行
1034
+ alembic upgrade head
1035
+ ```
1036
+
1037
+ ### 4. bcrypt Password Hashing Error
1038
+
1039
+ **症状**: `Password too long` エラー
1040
+
1041
+ **解決方法**:
1042
+ パスワードは自動的に72バイトに切り詰められます。`backend/app/utils/password_hash.py` 参照。
1043
+
1044
+ ### 5. WebSocket Connection Failed
1045
+
1046
+ **症状**: WebSocket接続が確立できない
1047
+
1048
+ **解決方法**:
1049
+ ```bash
1050
+ # CORS設定確認
1051
+ # backend/app/main.py の CORSMiddleware 設定を確認
1052
+
1053
+ # WebSocketサポート確認
1054
+ pip install websockets
1055
+
1056
+ # ファイアウォール確認
1057
+ sudo ufw allow 8000 # Linux
1058
+ ```
1059
+
1060
+ ### 6. HuggingFace Space Error
1061
+
1062
+ **症状**: `ImportError: cannot import name 'HfFolder'`
1063
+
1064
+ **解決方法**:
1065
+ ```bash
1066
+ # requirements.txtに正しいバージョンを指定
1067
+ echo "huggingface_hub==0.19.4" > requirements.txt
1068
+ huggingface-cli upload kofdai/null-ai requirements.txt --repo-type space
1069
+ ```
1070
+
1071
+ ---
1072
+
1073
+ ## 開発ガイドライン
1074
+
1075
+ ### コーディング規約
1076
+
1077
+ #### Python (PEP 8準拠)
1078
+ ```python
1079
+ # 良い例
1080
+ def process_question(question: str, domain: str) -> dict:
1081
+ """
1082
+ 質問を処理し、応答を生成する
1083
+
1084
+ Args:
1085
+ question: ユーザーの質問
1086
+ domain: ドメインID (medical/legal/general)
1087
+
1088
+ Returns:
1089
+ 応答辞書 {answer, confidence, sources}
1090
+ """
1091
+ pass
1092
+
1093
+ # 悪い例
1094
+ def pq(q, d): # 不明瞭な変数名
1095
+ pass
1096
+ ```
1097
+
1098
+ #### TypeScript
1099
+ ```typescript
1100
+ // 良い例
1101
+ interface Question {
1102
+ id: string;
1103
+ content: string;
1104
+ domain: DomainType;
1105
+ timestamp: Date;
1106
+ }
1107
+
1108
+ // 悪い例
1109
+ let q: any; // any型の乱用
1110
+ ```
1111
+
1112
+ ### Git コミットメッセージ
1113
+
1114
+ ```
1115
+ <type>(<scope>): <subject>
1116
+
1117
+ <body>
1118
+
1119
+ <footer>
1120
+ ```
1121
+
1122
+ **Types:**
1123
+ - `feat`: 新機能
1124
+ - `fix`: バグ修正
1125
+ - `docs`: ドキュメント
1126
+ - `style`: コードスタイル
1127
+ - `refactor`: リファクタリング
1128
+ - `test`: テスト
1129
+ - `chore`: ビルド・ツール
1130
+
1131
+ **例:**
1132
+ ```
1133
+ feat(inference): Add hallucination detection
1134
+
1135
+ Implement hallucination detection mechanism in Judge Beta Advanced
1136
+ using cosine similarity between generated response and source knowledge tiles.
1137
+
1138
+ Closes #123
1139
+ ```
1140
+
1141
+ ### テスト
1142
+
1143
+ #### バックエンドテスト
1144
+ ```bash
1145
+ # ユニットテスト
1146
+ pytest tests/unit/
1147
+
1148
+ # 統合テスト
1149
+ pytest tests/integration/
1150
+
1151
+ # カバレッジ
1152
+ pytest --cov=backend tests/
1153
+ ```
1154
+
1155
+ #### フロントエンドテスト
1156
+ ```bash
1157
+ # ユニットテスト
1158
+ npm test
1159
+
1160
+ # E2Eテスト
1161
+ npm run test:e2e
1162
+ ```
1163
+
1164
+ ---
1165
+
1166
+ ## パフォーマンス最適化
1167
+
1168
+ ### 1. モデル最適化
1169
+
1170
+ - **量子化**: 4-bit/8-bit量子化でメモリ削減
1171
+ - **Flash Attention**: 高速アテンション計算
1172
+ - **Model Pruning**: 不要なレイヤー削減
1173
+
1174
+ ### 2. キャッシング戦略
1175
+
1176
+ ```python
1177
+ # Hot Cache: 頻繁なクエリをメモリキャッシュ
1178
+ cache.set(query_hash, response, ttl=3600)
1179
+
1180
+ # Cold Cache: 長期保存はDB
1181
+ db.save_to_cache(query, response)
1182
+ ```
1183
+
1184
+ ### 3. データベースインデックス
1185
+
1186
+ ```sql
1187
+ -- 頻繁に検索されるカラムにインデックス
1188
+ CREATE INDEX idx_sessions_user_id ON sessions(user_id);
1189
+ CREATE INDEX idx_conv_history_created_at ON conversation_history(created_at DESC);
1190
+ ```
1191
+
1192
+ ---
1193
+
1194
+ ## セキュリティ
1195
+
1196
+ ### 1. 認証・認可
1197
+
1198
+ - **JWT**: トークンベース認証
1199
+ - **bcrypt**: パスワードハッシュ化 (salt rounds: 12)
1200
+ - **HTTPS**: 本番環境では必須
1201
+
1202
+ ### 2. 入力検証
1203
+
1204
+ ```python
1205
+ from pydantic import BaseModel, validator
1206
+
1207
+ class QuestionRequest(BaseModel):
1208
+ question: str
1209
+ domain_id: str
1210
+
1211
+ @validator('question')
1212
+ def validate_question(cls, v):
1213
+ if len(v) > 1000:
1214
+ raise ValueError('Question too long')
1215
+ return v
1216
+ ```
1217
+
1218
+ ### 3. レート制限
1219
+
1220
+ ```python
1221
+ from slowapi import Limiter
1222
+ from slowapi.util import get_remote_address
1223
+
1224
+ limiter = Limiter(key_func=get_remote_address)
1225
+
1226
+ @app.post("/api/questions/")
1227
+ @limiter.limit("10/minute")
1228
+ async def submit_question(request: Request):
1229
+ pass
1230
+ ```
1231
+
1232
+ ---
1233
+
1234
+ ## 監視・ログ
1235
+
1236
+ ### ログ設定
1237
+
1238
+ ```python
1239
+ import logging
1240
+
1241
+ logging.basicConfig(
1242
+ level=logging.INFO,
1243
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
1244
+ handlers=[
1245
+ logging.FileHandler('nullai.log'),
1246
+ logging.StreamHandler()
1247
+ ]
1248
+ )
1249
+
1250
+ logger = logging.getLogger(__name__)
1251
+ logger.info("Inference started", extra={"session_id": session_id})
1252
+ ```
1253
+
1254
+ ### メトリクス収集
1255
+
1256
+ - **Prometheus**: メトリクス収集
1257
+ - **Grafana**: ダッシュボード
1258
+ - **Sentry**: エラートラッキング
1259
+
1260
+ ---
1261
+
1262
+ ## 参考リンク
1263
+
1264
+ - [FastAPI Documentation](https://fastapi.tiangolo.com/)
1265
+ - [React Documentation](https://react.dev/)
1266
+ - [HuggingFace Transformers](https://huggingface.co/docs/transformers)
1267
+ - [PostgreSQL Documentation](https://www.postgresql.org/docs/)
1268
+ - [DeepSeek Model Card](https://huggingface.co/deepseek-ai/DeepSeek-R1-Distill-Qwen-32B)
1269
+
1270
+ ---
1271
+
1272
+ ## ライセンス
1273
+
1274
+ MIT License
1275
+
1276
+ ---
1277
+
1278
+ ## コントリビューション
1279
+
1280
+ プルリクエストを歓迎します。大きな変更の場合は、まずIssueで議論してください。
1281
+
1282
+ ---
1283
+
1284
+ **最終更新**: 2025-01-26
1285
+ **バージョン**: 1.0.0
1286
+ **メンテナ**: NULL AI Team