github-actions[bot] commited on
Commit
1798d15
ยท
1 Parent(s): b03cae4

deploy: backend from db5d8bb

Browse files
.env.example CHANGED
@@ -10,8 +10,8 @@ EMBEDDING_MODEL=BAAI/bge-small-en-v1.5
10
  # DeepSeek API key (OpenAI-compatible), required for all AI features
11
  DEEPSEEK_API_KEY=your_deepseek_api_key_here
12
  DEEPSEEK_BASE_URL=https://api.deepseek.com
13
- DEEPSEEK_MODEL=deepseek-chat
14
- DEEPSEEK_REASONER_MODEL=deepseek-reasoner
15
 
16
  # โ”€โ”€ HuggingFace (dataset push / HF Space deployment only) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
17
  # HF API token โ€” kept only for HF Space deployment and dataset push
@@ -19,11 +19,11 @@ HF_API_TOKEN=hf_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
19
 
20
 
21
  # โ”€โ”€ Model Selection โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
22
- # LOCAL DEVELOPMENT โ€” deepseek-chat (fast, $0.14/M input)
23
- HF_MODEL_ID=deepseek-chat
24
 
25
- # PRODUCTION โ€” deepseek-reasoner for step-by-step solutions
26
- # HF_MODEL_ID=deepseek-reasoner
27
 
28
  # โ”€โ”€ Quiz Battle Internal Auth โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
29
  # Shared secret between Firebase Cloud Functions and FastAPI backend
 
10
  # DeepSeek API key (OpenAI-compatible), required for all AI features
11
  DEEPSEEK_API_KEY=your_deepseek_api_key_here
12
  DEEPSEEK_BASE_URL=https://api.deepseek.com
13
+ DEEPSEEK_MODEL=deepseek-flash
14
+ DEEPSEEK_REASONER_MODEL=deepseek-v4-pro
15
 
16
  # โ”€โ”€ HuggingFace (dataset push / HF Space deployment only) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
17
  # HF API token โ€” kept only for HF Space deployment and dataset push
 
19
 
20
 
21
  # โ”€โ”€ Model Selection โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
22
+ # LOCAL DEVELOPMENT โ€” deepseek-flash (fast, $0.14/M input)
23
+ HF_MODEL_ID=deepseek-flash
24
 
25
+ # PRODUCTION โ€” deepseek-v4-pro for step-by-step solutions
26
+ # HF_MODEL_ID=deepseek-v4-pro
27
 
28
  # โ”€โ”€ Quiz Battle Internal Auth โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
29
  # Shared secret between Firebase Cloud Functions and FastAPI backend
config/ai_pricing.py CHANGED
@@ -1,6 +1,6 @@
1
  # backend/config/ai_pricing.py
2
  # DeepSeek V4 API Pricing Configuration
3
- # TODO: Review pricing after 2026-05-31
4
 
5
  from datetime import datetime, timezone
6
 
@@ -14,15 +14,15 @@ DEEPSEEK_PRICING = {
14
  "output_per_1m": 0.87,
15
  },
16
  "full_price": {
17
- "input_cache_hit_per_1m": 0.0145,
18
- "input_cache_miss_per_1m": 1.74,
19
- "output_per_1m": 3.48,
20
  },
21
  },
22
- "deepseek-v4-flash": {
23
- "input_cache_hit_per_1m": 0.0028,
24
- "input_cache_miss_per_1m": 0.14,
25
- "output_per_1m": 0.28,
26
  },
27
  }
28
 
 
1
  # backend/config/ai_pricing.py
2
  # DeepSeek V4 API Pricing Configuration
3
+ # Peak-hour rates from api-docs.deepseek.com/quick_start/pricing (2026-10); off-peak is half.
4
 
5
  from datetime import datetime, timezone
6
 
 
14
  "output_per_1m": 0.87,
15
  },
16
  "full_price": {
17
+ "input_cache_hit_per_1m": 0.044,
18
+ "input_cache_miss_per_1m": 1.32,
19
+ "output_per_1m": 3.96,
20
  },
21
  },
22
+ "deepseek-flash": {
23
+ "input_cache_hit_per_1m": 0.006,
24
+ "input_cache_miss_per_1m": 0.3,
25
+ "output_per_1m": 1.2,
26
  },
27
  }
28
 
config/codemap.md CHANGED
@@ -5,7 +5,7 @@ Holds model routing and AI API cost configuration: `models.yaml` defines generat
5
 
6
  ## Design
7
  - `models.yaml` is declarative: `models`, `model_capabilities`, `routing.task_model_map`, `task_fallback_model_map`, and `task_provider_map`.
8
- - `deepseek-reasoner` is sequential-only and enabled for reasoning tasks; fallback routes use `deepseek-chat`. Embeddings use `BAAI/bge-small-en-v1.5` and are configured separately from generation.
9
  - `DEEPSEEK_PRICING` contains per-million-token cache-hit, cache-miss, and output rates; promotional expiry is compared with UTC at call time.
10
  - `get_active_pricing(model_id)` and `get_full_pricing(model_id)` return pricing dictionaries and raise `ValueError` for unknown IDs.
11
 
 
5
 
6
  ## Design
7
  - `models.yaml` is declarative: `models`, `model_capabilities`, `routing.task_model_map`, `task_fallback_model_map`, and `task_provider_map`.
8
+ - `deepseek-v4-pro` is sequential-only and enabled for reasoning tasks; fallback routes use `deepseek-flash`. Embeddings use `BAAI/bge-small-en-v1.5` and are configured separately from generation.
9
  - `DEEPSEEK_PRICING` contains per-million-token cache-hit, cache-miss, and output rates; promotional expiry is compared with UTC at call time.
10
  - `get_active_pricing(model_id)` and `get_full_pricing(model_id)` return pricing dictionaries and raise `ValueError` for unknown IDs.
11
 
config/env.sample CHANGED
@@ -1,8 +1,8 @@
1
  # DeepSeek AI API (OpenAI-compatible)
2
  DEEPSEEK_API_KEY=your_deepseek_api_key_here
3
  DEEPSEEK_BASE_URL=https://api.deepseek.com
4
- DEEPSEEK_MODEL=deepseek-chat
5
- DEEPSEEK_REASONER_MODEL=deepseek-reasoner
6
  DEEPSEEK_ENABLED=true
7
 
8
  # Inference provider selection
@@ -72,13 +72,13 @@ APP_BRAND_AVATAR_URL=
72
 
73
  # model defaults
74
  # Global default model for all tasks.
75
- INFERENCE_MODEL_ID=deepseek-chat
76
  INFERENCE_ENFORCE_QWEN_ONLY=true
77
- INFERENCE_QWEN_LOCK_MODEL=deepseek-chat
78
  INFERENCE_MAX_NEW_TOKENS=8192
79
  INFERENCE_TEMPERATURE=0.2
80
  INFERENCE_TOP_P=0.9
81
- INFERENCE_CHAT_MODEL_ID=deepseek-chat
82
  # Temporary chat-only override for experiments (clear to roll back instantly).
83
  # Example: Qwen/Qwen3-32B
84
  INFERENCE_CHAT_MODEL_TEMP_OVERRIDE=
@@ -98,7 +98,7 @@ CHAT_STREAM_CONTINUATION_TAIL_CHARS=900
98
  CHAT_STREAM_COMPLETION_MODE_DEFAULT=auto
99
  # Optional: force quiz-generation model. Leave empty to use routing.task_model_map.quiz_generation.
100
  HF_QUIZ_MODEL_ID=
101
- HF_QUIZ_JSON_REPAIR_MODEL_ID=deepseek-chat
102
 
103
  # retry behavior
104
  INFERENCE_MAX_RETRIES=3
 
1
  # DeepSeek AI API (OpenAI-compatible)
2
  DEEPSEEK_API_KEY=your_deepseek_api_key_here
3
  DEEPSEEK_BASE_URL=https://api.deepseek.com
4
+ DEEPSEEK_MODEL=deepseek-flash
5
+ DEEPSEEK_REASONER_MODEL=deepseek-v4-pro
6
  DEEPSEEK_ENABLED=true
7
 
8
  # Inference provider selection
 
72
 
73
  # model defaults
74
  # Global default model for all tasks.
75
+ INFERENCE_MODEL_ID=deepseek-flash
76
  INFERENCE_ENFORCE_QWEN_ONLY=true
77
+ INFERENCE_QWEN_LOCK_MODEL=deepseek-flash
78
  INFERENCE_MAX_NEW_TOKENS=8192
79
  INFERENCE_TEMPERATURE=0.2
80
  INFERENCE_TOP_P=0.9
81
+ INFERENCE_CHAT_MODEL_ID=deepseek-flash
82
  # Temporary chat-only override for experiments (clear to roll back instantly).
83
  # Example: Qwen/Qwen3-32B
84
  INFERENCE_CHAT_MODEL_TEMP_OVERRIDE=
 
98
  CHAT_STREAM_COMPLETION_MODE_DEFAULT=auto
99
  # Optional: force quiz-generation model. Leave empty to use routing.task_model_map.quiz_generation.
100
  HF_QUIZ_MODEL_ID=
101
+ HF_QUIZ_JSON_REPAIR_MODEL_ID=deepseek-flash
102
 
103
  # retry behavior
104
  INFERENCE_MAX_RETRIES=3
config/models.yaml CHANGED
@@ -1,13 +1,13 @@
1
  models:
2
  primary:
3
- id: deepseek-chat
4
  description: Default DeepSeek chat model โ€” all chat tasks, quizzes, lessons, reasoning
5
  max_new_tokens: 800
6
  temperature: 0.7
7
  top_p: 0.9
8
 
9
  rag_primary:
10
- id: deepseek-reasoner
11
  description: DeepSeek reasoner โ€” extended reasoning for complex RAG tasks
12
  max_new_tokens: 1800
13
  temperature: 0.2
@@ -28,50 +28,50 @@ models:
28
 
29
  model_capabilities:
30
  sequential_only:
31
- - deepseek-reasoner
32
  supports_thinking:
33
- - deepseek-reasoner
34
 
35
  routing:
36
  task_model_map:
37
- chat: deepseek-chat
38
- verify_solution: deepseek-chat
39
- lesson_generation: deepseek-chat
40
- quiz_generation: deepseek-chat
41
- practice_generation: deepseek-chat
42
- learning_path: deepseek-chat
43
- daily_insight: deepseek-chat
44
- risk_classification: deepseek-chat
45
- risk_narrative: deepseek-reasoner
46
- rag_lesson: deepseek-reasoner
47
- rag_problem: deepseek-chat
48
- rag_analysis_context: deepseek-chat
49
 
50
  task_fallback_model_map:
51
  chat:
52
- - deepseek-chat
53
  verify_solution:
54
- - deepseek-chat
55
  lesson_generation:
56
- - deepseek-chat
57
  quiz_generation:
58
- - deepseek-chat
59
  practice_generation:
60
- - deepseek-chat
61
  learning_path:
62
- - deepseek-chat
63
  daily_insight:
64
- - deepseek-chat
65
  risk_classification:
66
- - deepseek-chat
67
  risk_narrative:
68
- - deepseek-chat
69
  rag_lesson:
70
- - deepseek-chat
71
  rag_problem:
72
- - deepseek-chat
73
  rag_analysis_context:
74
- - deepseek-chat
75
 
76
  task_provider_map:
77
  chat: deepseek
 
1
  models:
2
  primary:
3
+ id: deepseek-flash
4
  description: Default DeepSeek chat model โ€” all chat tasks, quizzes, lessons, reasoning
5
  max_new_tokens: 800
6
  temperature: 0.7
7
  top_p: 0.9
8
 
9
  rag_primary:
10
+ id: deepseek-v4-pro
11
  description: DeepSeek reasoner โ€” extended reasoning for complex RAG tasks
12
  max_new_tokens: 1800
13
  temperature: 0.2
 
28
 
29
  model_capabilities:
30
  sequential_only:
31
+ - deepseek-v4-pro
32
  supports_thinking:
33
+ - deepseek-v4-pro
34
 
35
  routing:
36
  task_model_map:
37
+ chat: deepseek-flash
38
+ verify_solution: deepseek-flash
39
+ lesson_generation: deepseek-flash
40
+ quiz_generation: deepseek-flash
41
+ practice_generation: deepseek-flash
42
+ learning_path: deepseek-flash
43
+ daily_insight: deepseek-flash
44
+ risk_classification: deepseek-flash
45
+ risk_narrative: deepseek-v4-pro
46
+ rag_lesson: deepseek-v4-pro
47
+ rag_problem: deepseek-flash
48
+ rag_analysis_context: deepseek-flash
49
 
50
  task_fallback_model_map:
51
  chat:
52
+ - deepseek-flash
53
  verify_solution:
54
+ - deepseek-flash
55
  lesson_generation:
56
+ - deepseek-flash
57
  quiz_generation:
58
+ - deepseek-flash
59
  practice_generation:
60
+ - deepseek-flash
61
  learning_path:
62
+ - deepseek-flash
63
  daily_insight:
64
+ - deepseek-flash
65
  risk_classification:
66
+ - deepseek-flash
67
  risk_narrative:
68
+ - deepseek-flash
69
  rag_lesson:
70
+ - deepseek-flash
71
  rag_problem:
72
+ - deepseek-flash
73
  rag_analysis_context:
74
+ - deepseek-flash
75
 
76
  task_provider_map:
77
  chat: deepseek
main.py CHANGED
@@ -36,6 +36,12 @@ from threading import Lock
36
  # Lazy import for audit_logger to prevent ModuleNotFoundError during test collection.
37
  # All call sites use asyncio.create_task() so delaying the import is safe.
38
  _audit_logger = None
 
 
 
 
 
 
39
  def _get_audit_logger():
40
  global _audit_logger
41
  if _audit_logger is None:
@@ -43,7 +49,9 @@ def _get_audit_logger():
43
  from services.audit_logger import log_audit_event as _fn
44
  _audit_logger = _fn
45
  except ImportError:
46
- _audit_logger = False # sentinel: don't retry
 
 
47
  # Load local environment variables from .env.local / .env before startup validation
48
  from pathlib import Path
49
  try:
@@ -286,14 +294,14 @@ HF_TOKEN = os.environ.get(
286
  ) # Kept for HF Space deployment / dataset push only; AI inference uses DEEPSEEK_API_KEY
287
 
288
  # Grade 11 tutoring default model. Can be overridden via INFERENCE_MODEL_ID or INFERENCE_CHAT_MODEL_ID.
289
- HF_MATH_MODEL_ID = os.getenv("INFERENCE_CHAT_MODEL_ID") or os.getenv("INFERENCE_MODEL_ID") or os.getenv("HF_MATH_MODEL_ID", "deepseek-chat")
290
 
291
  # Alias kept so automation_engine.py (which imports CHAT_MODEL) keeps working.
292
  CHAT_MODEL = HF_MATH_MODEL_ID
293
 
294
  # Dedicated quiz model override. When empty, routing.task_model_map decides quiz model.
295
  HF_QUIZ_MODEL_ID = (os.getenv("HF_QUIZ_MODEL_ID", "").strip() or None)
296
- HF_QUIZ_JSON_REPAIR_MODEL_ID = os.getenv("HF_QUIZ_JSON_REPAIR_MODEL_ID", "deepseek-chat")
297
 
298
  RISK_MODEL = CHAT_MODEL
299
  VERIFICATION_SAMPLES = 3 # Number of samples for self-consistency checking
@@ -449,7 +457,7 @@ ROLE_POLICIES: Dict[str, Set[str]] = {
449
  "/api/rag/lesson/stream": ALL_APP_ROLES,
450
  "/api/rag/lesson/prefetch": ALL_APP_ROLES,
451
  "/api/rag/generate-problem": TEACHER_OR_ADMIN,
452
- "/api/rag/analysis-context": TEACHER_OR_ADMIN,
453
  "/api/rag/documents/by-subject/{subject}": ADMIN_ONLY,
454
  "/api/rag/documents/by-source": ADMIN_ONLY,
455
  "/api/rag/documents/all": ADMIN_ONLY,
@@ -566,7 +574,7 @@ async def app_lifespan(_app: FastAPI) -> AsyncIterator[None]:
566
  logger.warning(f"โš ๏ธ Failed to pre-initialize InferenceClient: {e}")
567
 
568
  async def _warmup_vectorstore() -> None:
569
- active_model = os.getenv("HF_MODEL_ID", "deepseek-chat")
570
  try:
571
  from rag.vectorstore_loader import get_vectorstore_health
572
  health = await asyncio.to_thread(get_vectorstore_health)
@@ -1392,7 +1400,7 @@ app.add_middleware(
1392
  # โ”€โ”€โ”€ DeepSeek AI Clients โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
1393
 
1394
  # Zero-shot classification replaced with DeepSeek chat-based classification.
1395
- # BART risk model replaced with deepseek-chat structured output.
1396
 
1397
  from services.ai_client import get_deepseek_client, CHAT_MODEL, REASONER_MODEL, APIError, RateLimitError, APITimeoutError
1398
 
@@ -1706,7 +1714,7 @@ async def call_hf_chat_stream_async(
1706
  yield str(chunk)
1707
 
1708
 
1709
- def load_local_math_model(model_name: str = "deepseek-chat"):
1710
  """Optional local loader โ€” deprecated in favor of DeepSeek API."""
1711
  raise NotImplementedError(
1712
  "Local model loading is deprecated. Use DeepSeek API via DEEPSEEK_API_KEY env var."
 
36
  # Lazy import for audit_logger to prevent ModuleNotFoundError during test collection.
37
  # All call sites use asyncio.create_task() so delaying the import is safe.
38
  _audit_logger = None
39
+
40
+
41
+ async def _skip_audit_event(**_event: Any) -> None:
42
+ """Stands in for log_audit_event when services.audit_logger cannot be imported."""
43
+
44
+
45
  def _get_audit_logger():
46
  global _audit_logger
47
  if _audit_logger is None:
 
49
  from services.audit_logger import log_audit_event as _fn
50
  _audit_logger = _fn
51
  except ImportError:
52
+ _audit_logger = _skip_audit_event # don't retry the import
53
+ return _audit_logger
54
+
55
  # Load local environment variables from .env.local / .env before startup validation
56
  from pathlib import Path
57
  try:
 
294
  ) # Kept for HF Space deployment / dataset push only; AI inference uses DEEPSEEK_API_KEY
295
 
296
  # Grade 11 tutoring default model. Can be overridden via INFERENCE_MODEL_ID or INFERENCE_CHAT_MODEL_ID.
297
+ HF_MATH_MODEL_ID = os.getenv("INFERENCE_CHAT_MODEL_ID") or os.getenv("INFERENCE_MODEL_ID") or os.getenv("HF_MATH_MODEL_ID", "deepseek-flash")
298
 
299
  # Alias kept so automation_engine.py (which imports CHAT_MODEL) keeps working.
300
  CHAT_MODEL = HF_MATH_MODEL_ID
301
 
302
  # Dedicated quiz model override. When empty, routing.task_model_map decides quiz model.
303
  HF_QUIZ_MODEL_ID = (os.getenv("HF_QUIZ_MODEL_ID", "").strip() or None)
304
+ HF_QUIZ_JSON_REPAIR_MODEL_ID = os.getenv("HF_QUIZ_JSON_REPAIR_MODEL_ID", "deepseek-flash")
305
 
306
  RISK_MODEL = CHAT_MODEL
307
  VERIFICATION_SAMPLES = 3 # Number of samples for self-consistency checking
 
457
  "/api/rag/lesson/stream": ALL_APP_ROLES,
458
  "/api/rag/lesson/prefetch": ALL_APP_ROLES,
459
  "/api/rag/generate-problem": TEACHER_OR_ADMIN,
460
+ "/api/rag/analysis-context": ALL_APP_ROLES,
461
  "/api/rag/documents/by-subject/{subject}": ADMIN_ONLY,
462
  "/api/rag/documents/by-source": ADMIN_ONLY,
463
  "/api/rag/documents/all": ADMIN_ONLY,
 
574
  logger.warning(f"โš ๏ธ Failed to pre-initialize InferenceClient: {e}")
575
 
576
  async def _warmup_vectorstore() -> None:
577
+ active_model = os.getenv("HF_MODEL_ID", "deepseek-flash")
578
  try:
579
  from rag.vectorstore_loader import get_vectorstore_health
580
  health = await asyncio.to_thread(get_vectorstore_health)
 
1400
  # โ”€โ”€โ”€ DeepSeek AI Clients โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
1401
 
1402
  # Zero-shot classification replaced with DeepSeek chat-based classification.
1403
+ # BART risk model replaced with deepseek-flash structured output.
1404
 
1405
  from services.ai_client import get_deepseek_client, CHAT_MODEL, REASONER_MODEL, APIError, RateLimitError, APITimeoutError
1406
 
 
1714
  yield str(chunk)
1715
 
1716
 
1717
+ def load_local_math_model(model_name: str = "deepseek-flash"):
1718
  """Optional local loader โ€” deprecated in favor of DeepSeek API."""
1719
  raise NotImplementedError(
1720
  "Local model loading is deprecated. Use DeepSeek API via DEEPSEEK_API_KEY env var."
routes/admin_model_routes.py CHANGED
@@ -37,9 +37,9 @@ def get_model_config(_admin=Depends(require_admin)):
37
  **get_current_runtime_config(),
38
  "availableProfiles": list(_MODEL_PROFILES.keys()),
39
  "profileDescriptions": {
40
- "dev": "deepseek-chat everywhere - fast, $0.14/M input",
41
- "budget": "deepseek-chat for all tasks - minimal cost",
42
- "prod": "deepseek-reasoner for RAG, deepseek-chat for chat - best quality",
43
  },
44
  }
45
 
 
37
  **get_current_runtime_config(),
38
  "availableProfiles": list(_MODEL_PROFILES.keys()),
39
  "profileDescriptions": {
40
+ "dev": "deepseek-flash everywhere - fast, $0.30/M input",
41
+ "budget": "deepseek-flash for all tasks - minimal cost",
42
+ "prod": "deepseek-v4-pro for RAG, deepseek-flash for chat - best quality",
43
  },
44
  }
45
 
routes/diagnostic.py CHANGED
@@ -999,7 +999,8 @@ Return ONLY valid JSON, no markdown fences."""
999
  from main import call_hf_chat_async # noqa: E402
1000
  raw = await call_hf_chat_async(
1001
  [{"role": "user", "content": prompt}],
1002
- max_tokens=1500,
 
1003
  temperature=0.3,
1004
  task_type="analytics",
1005
  )
 
999
  from main import call_hf_chat_async # noqa: E402
1000
  raw = await call_hf_chat_async(
1001
  [{"role": "user", "content": prompt}],
1002
+ # The analysis JSON alone runs ~1.7k tokens; 1500 cut it mid-string and forced the fallback.
1003
+ max_tokens=4096,
1004
  temperature=0.3,
1005
  task_type="analytics",
1006
  )
routes/rag_routes.py CHANGED
@@ -68,9 +68,9 @@ def _lesson_primary_model() -> str:
68
  """Model for rag_lesson generation.
69
 
70
  An explicit RAG model (HF_RAG_MODEL_ID via admin override, MODEL_PROFILE or env) wins: the prod profile
71
- also exports INFERENCE_MODEL_ID=deepseek-chat, which overrides every task in the inference client's map.
72
- With no RAG model configured, fall back to the client's task map (config/models.yaml โ†’ deepseek-reasoner),
73
- since get_model_for_task() would otherwise resolve to deepseek-chat.
74
  """
75
  if get_current_runtime_config()["resolved"].get("HF_RAG_MODEL_ID"):
76
  return get_model_for_task("rag_lesson")
@@ -392,6 +392,12 @@ _LEARNER_PROFILE_CAP_SEC = 4.0
392
  _LEARNER_PROFILE_MAX_CHARS = 1500
393
  _LESSON_PROGRESS_INTERVAL_SEC = 1.0
394
  _LESSON_PING_INTERVAL_SEC = 15.0
 
 
 
 
 
 
395
  _REASONER_STREAM_TIMEOUT = httpx.Timeout(connect=10.0, read=60.0, write=30.0, pool=10.0)
396
  _STUDENT_LESSONS_COLLECTION = "studentLessons"
397
  GENERIC_LEARNER_PROFILE = (
@@ -637,13 +643,16 @@ def _stream_reasoner_lesson(
637
  ) -> str:
638
  """Stream a lesson from DeepSeek in a worker thread; returns the accumulated answer content."""
639
  client = get_deepseek_client().with_options(max_retries=0)
640
- # Reasoner rejects sampling params, and its reasoning tokens count toward max_tokens.
 
641
  stream = client.chat.completions.create(
642
  model=model,
643
  messages=messages,
644
- max_tokens=8192,
 
645
  stream=True,
646
  timeout=_REASONER_STREAM_TIMEOUT,
 
647
  )
648
  parts: List[str] = []
649
  content_chars = 0
 
68
  """Model for rag_lesson generation.
69
 
70
  An explicit RAG model (HF_RAG_MODEL_ID via admin override, MODEL_PROFILE or env) wins: the prod profile
71
+ also exports INFERENCE_MODEL_ID=deepseek-flash, which overrides every task in the inference client's map.
72
+ With no RAG model configured, fall back to the client's task map (config/models.yaml โ†’ deepseek-v4-pro),
73
+ since get_model_for_task() would otherwise resolve to deepseek-flash.
74
  """
75
  if get_current_runtime_config()["resolved"].get("HF_RAG_MODEL_ID"):
76
  return get_model_for_task("rag_lesson")
 
392
  _LEARNER_PROFILE_MAX_CHARS = 1500
393
  _LESSON_PROGRESS_INTERVAL_SEC = 1.0
394
  _LESSON_PING_INTERVAL_SEC = 15.0
395
+ _REASONER_LESSON_MAX_TOKENS = 32768
396
+ # The lesson is rewritten from retrieved curriculum text, so deep reasoning adds little; DeepSeek's default
397
+ # "high" effort took 61-221 s per lesson. Override with RAG_LESSON_REASONING_EFFORT=high|max if quality needs it.
398
+ _REASONER_LESSON_EFFORT = os.getenv("RAG_LESSON_REASONING_EFFORT", "low").strip().lower()
399
+ if _REASONER_LESSON_EFFORT not in {"low", "high", "max"}:
400
+ _REASONER_LESSON_EFFORT = "low"
401
  _REASONER_STREAM_TIMEOUT = httpx.Timeout(connect=10.0, read=60.0, write=30.0, pool=10.0)
402
  _STUDENT_LESSONS_COLLECTION = "studentLessons"
403
  GENERIC_LEARNER_PROFILE = (
 
643
  ) -> str:
644
  """Stream a lesson from DeepSeek in a worker thread; returns the accumulated answer content."""
645
  client = get_deepseek_client().with_options(max_retries=0)
646
+ # Thinking mode ignores sampling params, and its reasoning tokens count toward max_tokens:
647
+ # 8192 ran out mid-JSON on most lessons, so the budget leaves room for reasoning plus the lesson.
648
  stream = client.chat.completions.create(
649
  model=model,
650
  messages=messages,
651
+ max_tokens=_REASONER_LESSON_MAX_TOKENS,
652
+ reasoning_effort=_REASONER_LESSON_EFFORT,
653
  stream=True,
654
  timeout=_REASONER_STREAM_TIMEOUT,
655
+ extra_body={"thinking": {"type": "enabled"}},
656
  )
657
  parts: List[str] = []
658
  content_chars = 0
routes/teacher_materials.py CHANGED
@@ -307,7 +307,7 @@ Generate a teacher_uploaded module JSON following this exact schema:
307
  ],
308
  "aiSafety": {{
309
  "requiresGrounding": true,
310
- "allowedModels": ["deepseek-chat"],
311
  "groundingSources": ["teacher_file", "deped_rag"]
312
  }}
313
  }}
 
307
  ],
308
  "aiSafety": {{
309
  "requiresGrounding": true,
310
+ "allowedModels": ["deepseek-flash"],
311
  "groundingSources": ["teacher_file", "deped_rag"]
312
  }}
313
  }}
routes/tutor_checkin.py CHANGED
@@ -88,7 +88,7 @@ def generate_tutor_checkin(req: TutorCheckinRequest):
88
  # Call DeepSeek with a short, fast completion
89
  response = client.generate(
90
  messages=[{"role": "user", "content": prompt}],
91
- model="deepseek-chat",
92
  temperature=0.7,
93
  max_tokens=150,
94
  )
 
88
  # Call DeepSeek with a short, fast completion
89
  response = client.generate(
90
  messages=[{"role": "user", "content": prompt}],
91
+ model="deepseek-flash",
92
  temperature=0.7,
93
  max_tokens=150,
94
  )
services/ai_client.py CHANGED
@@ -20,6 +20,8 @@ __all__ = [
20
  "get_deepseek_client",
21
  "CHAT_MODEL",
22
  "REASONER_MODEL",
 
 
23
  "DEEPSEEK_BASE_URL",
24
  "APIError",
25
  "RateLimitError",
@@ -27,8 +29,23 @@ __all__ = [
27
  ]
28
 
29
  DEEPSEEK_BASE_URL = os.getenv("DEEPSEEK_BASE_URL", "https://api.deepseek.com")
30
- CHAT_MODEL = os.getenv("DEEPSEEK_MODEL", "deepseek-chat")
31
- REASONER_MODEL = os.getenv("DEEPSEEK_REASONER_MODEL", "deepseek-reasoner")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
 
33
 
34
  @lru_cache(maxsize=1)
@@ -36,8 +53,19 @@ def get_deepseek_client() -> OpenAI:
36
  api_key = os.getenv("DEEPSEEK_API_KEY")
37
  if not api_key:
38
  raise ValueError("DEEPSEEK_API_KEY environment variable not set")
39
- return OpenAI(
40
  api_key=api_key,
41
  base_url=DEEPSEEK_BASE_URL,
42
  max_retries=0, # retries are owned by InferenceClient; SDK retries would stack under them
43
  )
 
 
 
 
 
 
 
 
 
 
 
 
20
  "get_deepseek_client",
21
  "CHAT_MODEL",
22
  "REASONER_MODEL",
23
+ "thinking_body",
24
+ "current_model_id",
25
  "DEEPSEEK_BASE_URL",
26
  "APIError",
27
  "RateLimitError",
 
29
  ]
30
 
31
  DEEPSEEK_BASE_URL = os.getenv("DEEPSEEK_BASE_URL", "https://api.deepseek.com")
32
+ # API ids from GET /models: deepseek-flash serves V4.1-Flash, deepseek-v4-pro serves V4-Pro.
33
+ # Both think by default, so the thinking toggle is sent on every request (see get_deepseek_client).
34
+ # Retired DeepSeek names still sit in env vars and the Firestore model config; they resolve to the current ids.
35
+ _RETIRED_MODEL_IDS = {"deepseek-chat": "deepseek-flash", "deepseek-reasoner": "deepseek-v4-pro"}
36
+
37
+
38
+ def current_model_id(model: str) -> str:
39
+ return _RETIRED_MODEL_IDS.get(model, model)
40
+
41
+
42
+ CHAT_MODEL = current_model_id(os.getenv("DEEPSEEK_MODEL", "deepseek-flash"))
43
+ REASONER_MODEL = current_model_id(os.getenv("DEEPSEEK_REASONER_MODEL", "deepseek-v4-pro"))
44
+
45
+
46
+ def thinking_body(model: str) -> dict:
47
+ """DeepSeek's thinking toggle: on for the reasoner model, off for chat so fast tasks don't reason."""
48
+ return {"thinking": {"type": "enabled" if model == REASONER_MODEL else "disabled"}}
49
 
50
 
51
  @lru_cache(maxsize=1)
 
53
  api_key = os.getenv("DEEPSEEK_API_KEY")
54
  if not api_key:
55
  raise ValueError("DEEPSEEK_API_KEY environment variable not set")
56
+ client = OpenAI(
57
  api_key=api_key,
58
  base_url=DEEPSEEK_BASE_URL,
59
  max_retries=0, # retries are owned by InferenceClient; SDK retries would stack under them
60
  )
61
+ create = client.chat.completions.create
62
+
63
+ def create_with_thinking(*args, **kwargs):
64
+ if "model" in kwargs:
65
+ kwargs["model"] = current_model_id(kwargs["model"])
66
+ # An explicit extra_body "thinking" from the caller wins.
67
+ kwargs["extra_body"] = {**thinking_body(kwargs.get("model", "")), **(kwargs.get("extra_body") or {})}
68
+ return create(*args, **kwargs)
69
+
70
+ client.chat.completions.create = create_with_thinking # type: ignore[method-assign]
71
+ return client
services/inference_client.py CHANGED
@@ -42,7 +42,7 @@ try:
42
  except Exception:
43
  pass
44
 
45
- from .ai_client import get_deepseek_client, CHAT_MODEL, REASONER_MODEL, DEEPSEEK_BASE_URL
46
  from .logging_utils import configure_structured_logging, log_model_call
47
 
48
  LOGGER = configure_structured_logging("mathpulse.inference")
@@ -198,11 +198,11 @@ def get_current_runtime_config() -> dict:
198
 
199
  def _resolve_key(key: str) -> str:
200
  if value := _RUNTIME_OVERRIDES.get(key):
201
- return value
202
  if _RUNTIME_PROFILE and _RUNTIME_PROFILE in _MODEL_PROFILES:
203
  if value := _MODEL_PROFILES[_RUNTIME_PROFILE].get(key):
204
- return value
205
- return os.getenv(key, "")
206
 
207
 
208
  def get_model_for_task(task_type: str) -> str:
@@ -214,7 +214,7 @@ def get_model_for_task(task_type: str) -> str:
214
  or os.getenv("INFERENCE_LOCK_MODEL_ID")
215
  or CHAT_MODEL
216
  )
217
- return override
218
  task_key_map = {
219
  "chat": "INFERENCE_CHAT_MODEL_ID",
220
  "quiz_generation": "HF_QUIZ_MODEL_ID",
@@ -736,7 +736,8 @@ class InferenceClient:
736
  }
737
 
738
  if target_model == REASONER_MODEL:
739
- params["max_tokens"] = max(req.max_new_tokens or 4096, 4096)
 
740
  else:
741
  params["temperature"] = req.temperature
742
  params["top_p"] = req.top_p
 
42
  except Exception:
43
  pass
44
 
45
+ from .ai_client import get_deepseek_client, current_model_id, CHAT_MODEL, REASONER_MODEL, DEEPSEEK_BASE_URL
46
  from .logging_utils import configure_structured_logging, log_model_call
47
 
48
  LOGGER = configure_structured_logging("mathpulse.inference")
 
198
 
199
  def _resolve_key(key: str) -> str:
200
  if value := _RUNTIME_OVERRIDES.get(key):
201
+ return current_model_id(value)
202
  if _RUNTIME_PROFILE and _RUNTIME_PROFILE in _MODEL_PROFILES:
203
  if value := _MODEL_PROFILES[_RUNTIME_PROFILE].get(key):
204
+ return current_model_id(value)
205
+ return current_model_id(os.getenv(key, ""))
206
 
207
 
208
  def get_model_for_task(task_type: str) -> str:
 
214
  or os.getenv("INFERENCE_LOCK_MODEL_ID")
215
  or CHAT_MODEL
216
  )
217
+ return current_model_id(override)
218
  task_key_map = {
219
  "chat": "INFERENCE_CHAT_MODEL_ID",
220
  "quiz_generation": "HF_QUIZ_MODEL_ID",
 
736
  }
737
 
738
  if target_model == REASONER_MODEL:
739
+ # Reasoning tokens count toward max_tokens, so leave room past the answer budget.
740
+ params["max_tokens"] = max(req.max_new_tokens or 16384, 16384)
741
  else:
742
  params["temperature"] = req.temperature
743
  params["top_p"] = req.top_p
startup_validation.py CHANGED
@@ -204,13 +204,13 @@ def validate_environment() -> None:
204
  logger.info(f" โœ“ INFERENCE_PROVIDER: {inference_provider}")
205
 
206
  # Check model IDs
207
- chat_model = os.getenv("INFERENCE_CHAT_MODEL_ID") or os.getenv("INFERENCE_MODEL_ID") or "deepseek-chat"
208
  logger.info(f" โœ“ Chat model configured: {chat_model}")
209
 
210
  chat_strict = os.getenv("INFERENCE_CHAT_STRICT_MODEL_ONLY", "true").strip().lower() in {"1", "true", "yes", "on"}
211
  chat_hard_trigger = os.getenv("INFERENCE_CHAT_HARD_TRIGGER_ENABLED", "false").strip().lower() in {"1", "true", "yes", "on"}
212
  enforce_lock_model = os.getenv("INFERENCE_ENFORCE_LOCK_MODEL", "true").strip().lower() in {"1", "true", "yes", "on"}
213
- lock_model_id = os.getenv("INFERENCE_LOCK_MODEL_ID", "deepseek-chat").strip() or "deepseek-chat"
214
  logger.info(f" โœ“ INFERENCE_ENFORCE_LOCK_MODEL: {enforce_lock_model}")
215
  logger.info(f" โœ“ INFERENCE_LOCK_MODEL_ID: {lock_model_id}")
216
  model_profile = os.getenv("MODEL_PROFILE", "").strip().lower()
 
204
  logger.info(f" โœ“ INFERENCE_PROVIDER: {inference_provider}")
205
 
206
  # Check model IDs
207
+ chat_model = os.getenv("INFERENCE_CHAT_MODEL_ID") or os.getenv("INFERENCE_MODEL_ID") or "deepseek-flash"
208
  logger.info(f" โœ“ Chat model configured: {chat_model}")
209
 
210
  chat_strict = os.getenv("INFERENCE_CHAT_STRICT_MODEL_ONLY", "true").strip().lower() in {"1", "true", "yes", "on"}
211
  chat_hard_trigger = os.getenv("INFERENCE_CHAT_HARD_TRIGGER_ENABLED", "false").strip().lower() in {"1", "true", "yes", "on"}
212
  enforce_lock_model = os.getenv("INFERENCE_ENFORCE_LOCK_MODEL", "true").strip().lower() in {"1", "true", "yes", "on"}
213
+ lock_model_id = os.getenv("INFERENCE_LOCK_MODEL_ID", "deepseek-flash").strip() or "deepseek-flash"
214
  logger.info(f" โœ“ INFERENCE_ENFORCE_LOCK_MODEL: {enforce_lock_model}")
215
  logger.info(f" โœ“ INFERENCE_LOCK_MODEL_ID: {lock_model_id}")
216
  model_profile = os.getenv("MODEL_PROFILE", "").strip().lower()
tests/role_policy_expectations.py CHANGED
@@ -48,7 +48,7 @@ EXPECTED_ROLE_POLICIES = {
48
  "/api/rag/lesson/stream": ALL_ROLES,
49
  "/api/rag/lesson/prefetch": ALL_ROLES,
50
  "/api/rag/generate-problem": TEACHER_ADMIN,
51
- "/api/rag/analysis-context": TEACHER_ADMIN,
52
  "/api/rag/documents/by-subject/{subject}": ADMIN_ONLY,
53
  "/api/rag/documents/by-source": ADMIN_ONLY,
54
  "/api/rag/documents/all": ADMIN_ONLY,
 
48
  "/api/rag/lesson/stream": ALL_ROLES,
49
  "/api/rag/lesson/prefetch": ALL_ROLES,
50
  "/api/rag/generate-problem": TEACHER_ADMIN,
51
+ "/api/rag/analysis-context": ALL_ROLES,
52
  "/api/rag/documents/by-subject/{subject}": ADMIN_ONLY,
53
  "/api/rag/documents/by-source": ADMIN_ONLY,
54
  "/api/rag/documents/all": ADMIN_ONLY,
tests/test_ai_client_thinking.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """DeepSeek's current models think by default; the shared client must set the toggle per model."""
2
+ import os
3
+ import sys
4
+
5
+ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
6
+
7
+ import pytest
8
+
9
+ from services import ai_client
10
+
11
+
12
+ @pytest.fixture
13
+ def sent(monkeypatch: pytest.MonkeyPatch) -> list:
14
+ monkeypatch.setenv("DEEPSEEK_API_KEY", "test-key")
15
+ ai_client.get_deepseek_client.cache_clear()
16
+ client = ai_client.get_deepseek_client()
17
+ requests: list = []
18
+ # The SDK merges extra_body (options.extra_json) into the JSON body it sends.
19
+ monkeypatch.setattr(client.chat.completions, "_post", lambda *args, **kwargs: requests.append({**kwargs["body"], **(kwargs["options"].get("extra_json") or {})}))
20
+ yield requests
21
+ ai_client.get_deepseek_client.cache_clear()
22
+
23
+
24
+ def test_default_model_ids_are_current_api_ids() -> None:
25
+ assert ai_client.CHAT_MODEL == "deepseek-flash"
26
+ assert ai_client.REASONER_MODEL == "deepseek-v4-pro"
27
+
28
+
29
+ def test_chat_model_disables_thinking(sent: list) -> None:
30
+ ai_client.get_deepseek_client().chat.completions.create(model=ai_client.CHAT_MODEL, messages=[{"role": "user", "content": "hi"}])
31
+ assert sent[0]["thinking"] == {"type": "disabled"}
32
+
33
+
34
+ def test_reasoner_model_enables_thinking(sent: list) -> None:
35
+ ai_client.get_deepseek_client().chat.completions.create(model=ai_client.REASONER_MODEL, messages=[{"role": "user", "content": "hi"}])
36
+ assert sent[0]["thinking"] == {"type": "enabled"}
37
+
38
+
39
+ def test_caller_thinking_wins(sent: list) -> None:
40
+ ai_client.get_deepseek_client().chat.completions.create(
41
+ model=ai_client.CHAT_MODEL,
42
+ messages=[{"role": "user", "content": "hi"}],
43
+ extra_body={"thinking": {"type": "enabled"}},
44
+ )
45
+ assert sent[0]["thinking"] == {"type": "enabled"}
46
+
47
+
48
+ def test_retired_ids_map_to_current_ids(sent: list) -> None:
49
+ ai_client.get_deepseek_client().chat.completions.create(model="deepseek-reasoner", messages=[{"role": "user", "content": "hi"}])
50
+ assert sent[0]["model"] == "deepseek-v4-pro"
51
+ assert sent[0]["thinking"] == {"type": "enabled"}
52
+ assert ai_client.current_model_id("deepseek-chat") == "deepseek-flash"
53
+
54
+
55
+ def test_stale_firestore_override_resolves_to_current_id(monkeypatch: pytest.MonkeyPatch) -> None:
56
+ from services import inference_client
57
+
58
+ monkeypatch.setitem(inference_client._RUNTIME_OVERRIDES, "HF_RAG_MODEL_ID", "deepseek-reasoner")
59
+ assert inference_client.get_model_for_task("rag_lesson") == "deepseek-v4-pro"
tests/test_api.py CHANGED
@@ -598,7 +598,7 @@ class TestChatTransport:
598
 
599
  class TestInferenceRouting:
600
  def test_chat_strict_model_lock_keeps_single_model_chain(self, monkeypatch):
601
- monkeypatch.setenv("INFERENCE_CHAT_MODEL_ID", "deepseek-chat")
602
  monkeypatch.setenv("INFERENCE_CHAT_STRICT_MODEL_ONLY", "true")
603
 
604
  client = InferenceClient()
@@ -610,15 +610,15 @@ class TestInferenceRouting:
610
  selected_model, source = client._resolve_primary_model(req)
611
  model_chain = client._model_chain_for_task("chat", selected_model)
612
 
613
- assert selected_model == "deepseek-chat"
614
  assert "chat_strict_model_only" in source
615
- assert model_chain == ["deepseek-chat"]
616
 
617
  def test_chat_env_override_wins_under_model_lock(self, monkeypatch):
618
- monkeypatch.setenv("INFERENCE_CHAT_MODEL_ID", "deepseek-chat")
619
  monkeypatch.setenv("INFERENCE_CHAT_STRICT_MODEL_ONLY", "true")
620
  monkeypatch.setenv("INFERENCE_ENFORCE_LOCK_MODEL", "true")
621
- monkeypatch.setenv("INFERENCE_LOCK_MODEL_ID", "deepseek-reasoner")
622
 
623
  client = InferenceClient()
624
  req = InferenceRequest(
@@ -629,16 +629,16 @@ class TestInferenceRouting:
629
  selected_model, source = client._resolve_primary_model(req)
630
  model_chain = client._model_chain_for_task("chat", selected_model)
631
 
632
- assert selected_model == "deepseek-chat"
633
  assert "chat_override_env" in source
634
- assert model_chain == ["deepseek-chat"]
635
 
636
  def test_chat_temp_override_wins_under_model_lock(self, monkeypatch):
637
- monkeypatch.setenv("INFERENCE_CHAT_MODEL_ID", "deepseek-reasoner")
638
- monkeypatch.setenv("INFERENCE_CHAT_MODEL_TEMP_OVERRIDE", "deepseek-chat")
639
  monkeypatch.setenv("INFERENCE_CHAT_STRICT_MODEL_ONLY", "true")
640
  monkeypatch.setenv("INFERENCE_ENFORCE_LOCK_MODEL", "true")
641
- monkeypatch.setenv("INFERENCE_LOCK_MODEL_ID", "deepseek-reasoner")
642
 
643
  client = InferenceClient()
644
  req = InferenceRequest(
@@ -649,14 +649,14 @@ class TestInferenceRouting:
649
  selected_model, source = client._resolve_primary_model(req)
650
  model_chain = client._model_chain_for_task("chat", selected_model)
651
 
652
- assert selected_model == "deepseek-chat"
653
  assert "chat_temp_override_env" in source
654
- assert model_chain == ["deepseek-chat"]
655
 
656
  def test_chat_temp_override_does_not_change_non_chat_task_under_lock(self, monkeypatch):
657
- monkeypatch.setenv("INFERENCE_CHAT_MODEL_TEMP_OVERRIDE", "deepseek-chat")
658
  monkeypatch.setenv("INFERENCE_ENFORCE_LOCK_MODEL", "true")
659
- monkeypatch.setenv("INFERENCE_LOCK_MODEL_ID", "deepseek-reasoner")
660
 
661
  client = InferenceClient()
662
  req = InferenceRequest(
@@ -667,9 +667,9 @@ class TestInferenceRouting:
667
  selected_model, source = client._resolve_primary_model(req)
668
  model_chain = client._model_chain_for_task("verify_solution", selected_model)
669
 
670
- assert selected_model == "deepseek-reasoner"
671
  assert "chat_temp_override_env" not in source
672
- assert model_chain == ["deepseek-reasoner"]
673
 
674
 
675
  # โ”€โ”€โ”€ Risk Prediction โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
 
598
 
599
  class TestInferenceRouting:
600
  def test_chat_strict_model_lock_keeps_single_model_chain(self, monkeypatch):
601
+ monkeypatch.setenv("INFERENCE_CHAT_MODEL_ID", "deepseek-flash")
602
  monkeypatch.setenv("INFERENCE_CHAT_STRICT_MODEL_ONLY", "true")
603
 
604
  client = InferenceClient()
 
610
  selected_model, source = client._resolve_primary_model(req)
611
  model_chain = client._model_chain_for_task("chat", selected_model)
612
 
613
+ assert selected_model == "deepseek-flash"
614
  assert "chat_strict_model_only" in source
615
+ assert model_chain == ["deepseek-flash"]
616
 
617
  def test_chat_env_override_wins_under_model_lock(self, monkeypatch):
618
+ monkeypatch.setenv("INFERENCE_CHAT_MODEL_ID", "deepseek-flash")
619
  monkeypatch.setenv("INFERENCE_CHAT_STRICT_MODEL_ONLY", "true")
620
  monkeypatch.setenv("INFERENCE_ENFORCE_LOCK_MODEL", "true")
621
+ monkeypatch.setenv("INFERENCE_LOCK_MODEL_ID", "deepseek-v4-pro")
622
 
623
  client = InferenceClient()
624
  req = InferenceRequest(
 
629
  selected_model, source = client._resolve_primary_model(req)
630
  model_chain = client._model_chain_for_task("chat", selected_model)
631
 
632
+ assert selected_model == "deepseek-flash"
633
  assert "chat_override_env" in source
634
+ assert model_chain == ["deepseek-flash"]
635
 
636
  def test_chat_temp_override_wins_under_model_lock(self, monkeypatch):
637
+ monkeypatch.setenv("INFERENCE_CHAT_MODEL_ID", "deepseek-v4-pro")
638
+ monkeypatch.setenv("INFERENCE_CHAT_MODEL_TEMP_OVERRIDE", "deepseek-flash")
639
  monkeypatch.setenv("INFERENCE_CHAT_STRICT_MODEL_ONLY", "true")
640
  monkeypatch.setenv("INFERENCE_ENFORCE_LOCK_MODEL", "true")
641
+ monkeypatch.setenv("INFERENCE_LOCK_MODEL_ID", "deepseek-v4-pro")
642
 
643
  client = InferenceClient()
644
  req = InferenceRequest(
 
649
  selected_model, source = client._resolve_primary_model(req)
650
  model_chain = client._model_chain_for_task("chat", selected_model)
651
 
652
+ assert selected_model == "deepseek-flash"
653
  assert "chat_temp_override_env" in source
654
+ assert model_chain == ["deepseek-flash"]
655
 
656
  def test_chat_temp_override_does_not_change_non_chat_task_under_lock(self, monkeypatch):
657
+ monkeypatch.setenv("INFERENCE_CHAT_MODEL_TEMP_OVERRIDE", "deepseek-flash")
658
  monkeypatch.setenv("INFERENCE_ENFORCE_LOCK_MODEL", "true")
659
+ monkeypatch.setenv("INFERENCE_LOCK_MODEL_ID", "deepseek-v4-pro")
660
 
661
  client = InferenceClient()
662
  req = InferenceRequest(
 
667
  selected_model, source = client._resolve_primary_model(req)
668
  model_chain = client._model_chain_for_task("verify_solution", selected_model)
669
 
670
+ assert selected_model == "deepseek-v4-pro"
671
  assert "chat_temp_override_env" not in source
672
+ assert model_chain == ["deepseek-v4-pro"]
673
 
674
 
675
  # โ”€โ”€โ”€ Risk Prediction โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
tests/test_audit_logger_lookup.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """_get_audit_logger() returned None, so every access audit event raised 'NoneType' object is not callable."""
2
+ import inspect
3
+ import os
4
+ import sys
5
+
6
+ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
7
+
8
+ import main
9
+ from services.audit_logger import log_audit_event
10
+
11
+
12
+ def test_audit_logger_lookup_returns_the_event_writer() -> None:
13
+ assert main._get_audit_logger() is log_audit_event
14
+ assert inspect.iscoroutinefunction(main._get_audit_logger())
tests/test_cost_calculator.py CHANGED
@@ -1,5 +1,5 @@
1
  # backend/tests/test_cost_calculator.py
2
- """Tests for services/cost_calculator.py covering promo active, promo expired, V4 Flash, and edge cases."""
3
  import sys
4
  import os
5
  from unittest.mock import patch
@@ -69,22 +69,22 @@ class TestCalculateFeatureCostPromoExpired:
69
 
70
 
71
  class TestCalculateFeatureCostFlash:
72
- """Tests for deepseek-v4-flash (no promotional pricing)."""
73
 
74
  def test_flash_pricing(self):
75
  result = calculate_feature_cost(
76
- "deepseek-v4-flash",
77
  cache_hit_tokens=1_000_000,
78
  cache_miss_tokens=1_000_000,
79
  output_tokens=1_000_000,
80
  )
81
  assert result["is_promotional"] is False
82
- assert result["cache_hit_cost"] == round(0.0028, 6)
83
- assert result["cache_miss_cost"] == round(0.14, 6)
84
- assert result["output_cost"] == round(0.28, 6)
85
 
86
  def test_flash_zero_tokens(self):
87
- result = calculate_feature_cost("deepseek-v4-flash", 0, 0, 0)
88
  assert result["total_usd"] == 0.0
89
 
90
 
@@ -93,12 +93,12 @@ class TestCalculateFullPriceCost:
93
 
94
  def test_full_price_v4_pro(self):
95
  cost = calculate_full_price_cost("deepseek-v4-pro", 1_000_000, 1_000_000, 1_000_000)
96
- expected = 0.0145 + 1.74 + 3.48
97
  assert abs(cost - expected) < 1e-5
98
 
99
  def test_full_price_flash(self):
100
- cost = calculate_full_price_cost("deepseek-v4-flash", 1_000_000, 1_000_000, 1_000_000)
101
- expected = 0.0028 + 0.14 + 0.28
102
  assert abs(cost - expected) < 1e-5
103
 
104
 
 
1
  # backend/tests/test_cost_calculator.py
2
+ """Tests for services/cost_calculator.py covering promo active, promo expired, Flash, and edge cases."""
3
  import sys
4
  import os
5
  from unittest.mock import patch
 
69
 
70
 
71
  class TestCalculateFeatureCostFlash:
72
+ """Tests for deepseek-flash (no promotional pricing)."""
73
 
74
  def test_flash_pricing(self):
75
  result = calculate_feature_cost(
76
+ "deepseek-flash",
77
  cache_hit_tokens=1_000_000,
78
  cache_miss_tokens=1_000_000,
79
  output_tokens=1_000_000,
80
  )
81
  assert result["is_promotional"] is False
82
+ assert result["cache_hit_cost"] == round(0.006, 6)
83
+ assert result["cache_miss_cost"] == round(0.3, 6)
84
+ assert result["output_cost"] == round(1.2, 6)
85
 
86
  def test_flash_zero_tokens(self):
87
+ result = calculate_feature_cost("deepseek-flash", 0, 0, 0)
88
  assert result["total_usd"] == 0.0
89
 
90
 
 
93
 
94
  def test_full_price_v4_pro(self):
95
  cost = calculate_full_price_cost("deepseek-v4-pro", 1_000_000, 1_000_000, 1_000_000)
96
+ expected = 0.044 + 1.32 + 3.96
97
  assert abs(cost - expected) < 1e-5
98
 
99
  def test_full_price_flash(self):
100
+ cost = calculate_full_price_cost("deepseek-flash", 1_000_000, 1_000_000, 1_000_000)
101
+ expected = 0.006 + 0.3 + 1.2
102
  assert abs(cost - expected) < 1e-5
103
 
104
 
tests/test_model_profiles.py CHANGED
@@ -35,18 +35,18 @@ class TestModelProfiles:
35
  def test_dev_uses_chat_model(self):
36
  dev = _MODEL_PROFILES["dev"]
37
  for key, value in dev.items():
38
- assert "deepseek-chat" in value, f"dev/{key} = {value}, expected deepseek-chat"
39
 
40
  def test_prod_chat_is_chat_model(self):
41
- assert "deepseek-chat" in _MODEL_PROFILES["prod"]["INFERENCE_CHAT_MODEL_ID"]
42
 
43
  def test_prod_rag_is_reasoner(self):
44
- assert "deepseek-reasoner" in _MODEL_PROFILES["prod"]["HF_RAG_MODEL_ID"]
45
 
46
  def test_budget_uses_chat_model_everywhere(self):
47
  budget = _MODEL_PROFILES["budget"]
48
  for key, value in budget.items():
49
- assert "deepseek-chat" in value, f"budget/{key} = {value}"
50
 
51
 
52
  class TestRuntimeOverrides:
@@ -60,14 +60,14 @@ class TestRuntimeOverrides:
60
  def test_set_profile_populates_overrides(self):
61
  set_runtime_model_profile("dev")
62
  assert inf_client._RUNTIME_PROFILE == "dev"
63
- assert inf_client._RUNTIME_OVERRIDES["INFERENCE_MODEL_ID"] == "deepseek-chat"
64
- assert inf_client._RUNTIME_OVERRIDES["INFERENCE_CHAT_MODEL_ID"] == "deepseek-chat"
65
 
66
  def test_set_profile_replaces_all_overrides(self):
67
  set_runtime_model_profile("dev")
68
  set_runtime_model_profile("prod")
69
- assert inf_client._RUNTIME_OVERRIDES["INFERENCE_CHAT_MODEL_ID"] == "deepseek-chat"
70
- assert inf_client._RUNTIME_OVERRIDES["INFERENCE_LOCK_MODEL_ID"] == "deepseek-chat"
71
 
72
  def test_set_profile_unknown_raises(self):
73
  with pytest.raises(ValueError, match="Unknown profile"):
@@ -87,7 +87,7 @@ class TestRuntimeOverrides:
87
  set_runtime_model_profile("dev")
88
  set_runtime_model_override("HF_RAG_MODEL_ID", "custom/model")
89
  assert inf_client._RUNTIME_OVERRIDES["HF_RAG_MODEL_ID"] == "custom/model"
90
- assert inf_client._RUNTIME_OVERRIDES["INFERENCE_MODEL_ID"] == "deepseek-chat"
91
 
92
 
93
  class TestGetCurrentRuntimeConfig:
@@ -124,13 +124,13 @@ class TestGetModelForTask:
124
  def test_returns_profile_default_for_rag(self):
125
  set_runtime_model_profile("prod")
126
  model = get_model_for_task("rag_lesson")
127
- assert "deepseek-reasoner" in model
128
 
129
  @patch.dict(os.environ, {"INFERENCE_ENFORCE_LOCK_MODEL": "false"})
130
  def test_returns_profile_default_for_chat(self):
131
  set_runtime_model_profile("prod")
132
  model = get_model_for_task("chat")
133
- assert "deepseek-chat" in model
134
 
135
  @patch.dict(os.environ, {"INFERENCE_ENFORCE_LOCK_MODEL": "false"})
136
  def test_returns_runtime_override_for_chat(self):
@@ -142,7 +142,7 @@ class TestGetModelForTask:
142
  def test_enforce_qwen_overrides_task(self):
143
  set_runtime_model_profile("prod")
144
  model = get_model_for_task("rag_lesson")
145
- assert "deepseek-chat" in model
146
 
147
 
148
  class TestIsSequentialModel:
@@ -154,20 +154,20 @@ class TestIsSequentialModel:
154
  reset_runtime_overrides()
155
 
156
  def test_reasoner_is_sequential(self):
157
- assert is_sequential_model("deepseek-reasoner") is True
158
 
159
  def test_chat_is_not_sequential(self):
160
- assert is_sequential_model("deepseek-chat") is False
161
 
162
  def test_empty_string_checks_env(self):
163
  result = is_sequential_model("")
164
  assert result is True or result is False
165
 
166
- @patch.dict(os.environ, {"INFERENCE_MODEL_ID": "deepseek-reasoner"})
167
  def test_env_model_reasoner_is_sequential(self):
168
  assert is_sequential_model("") is True
169
 
170
- @patch.dict(os.environ, {"INFERENCE_MODEL_ID": "deepseek-chat"})
171
  def test_env_model_chat_is_not_sequential(self):
172
  assert is_sequential_model("") is False
173
 
@@ -175,10 +175,10 @@ class TestIsSequentialModel:
175
  class TestModelSupportsThinking:
176
 
177
  def test_reasoner_supports_thinking(self):
178
- assert model_supports_thinking("deepseek-reasoner") is True
179
 
180
  def test_chat_does_not_support_thinking(self):
181
- assert model_supports_thinking("deepseek-chat") is False
182
 
183
  def test_unknown_does_not_support_thinking(self):
184
  assert model_supports_thinking("meta-llama/Llama-3.1-8B-Instruct") is False
 
35
  def test_dev_uses_chat_model(self):
36
  dev = _MODEL_PROFILES["dev"]
37
  for key, value in dev.items():
38
+ assert "deepseek-flash" in value, f"dev/{key} = {value}, expected deepseek-flash"
39
 
40
  def test_prod_chat_is_chat_model(self):
41
+ assert "deepseek-flash" in _MODEL_PROFILES["prod"]["INFERENCE_CHAT_MODEL_ID"]
42
 
43
  def test_prod_rag_is_reasoner(self):
44
+ assert "deepseek-v4-pro" in _MODEL_PROFILES["prod"]["HF_RAG_MODEL_ID"]
45
 
46
  def test_budget_uses_chat_model_everywhere(self):
47
  budget = _MODEL_PROFILES["budget"]
48
  for key, value in budget.items():
49
+ assert "deepseek-flash" in value, f"budget/{key} = {value}"
50
 
51
 
52
  class TestRuntimeOverrides:
 
60
  def test_set_profile_populates_overrides(self):
61
  set_runtime_model_profile("dev")
62
  assert inf_client._RUNTIME_PROFILE == "dev"
63
+ assert inf_client._RUNTIME_OVERRIDES["INFERENCE_MODEL_ID"] == "deepseek-flash"
64
+ assert inf_client._RUNTIME_OVERRIDES["INFERENCE_CHAT_MODEL_ID"] == "deepseek-flash"
65
 
66
  def test_set_profile_replaces_all_overrides(self):
67
  set_runtime_model_profile("dev")
68
  set_runtime_model_profile("prod")
69
+ assert inf_client._RUNTIME_OVERRIDES["INFERENCE_CHAT_MODEL_ID"] == "deepseek-flash"
70
+ assert inf_client._RUNTIME_OVERRIDES["INFERENCE_LOCK_MODEL_ID"] == "deepseek-flash"
71
 
72
  def test_set_profile_unknown_raises(self):
73
  with pytest.raises(ValueError, match="Unknown profile"):
 
87
  set_runtime_model_profile("dev")
88
  set_runtime_model_override("HF_RAG_MODEL_ID", "custom/model")
89
  assert inf_client._RUNTIME_OVERRIDES["HF_RAG_MODEL_ID"] == "custom/model"
90
+ assert inf_client._RUNTIME_OVERRIDES["INFERENCE_MODEL_ID"] == "deepseek-flash"
91
 
92
 
93
  class TestGetCurrentRuntimeConfig:
 
124
  def test_returns_profile_default_for_rag(self):
125
  set_runtime_model_profile("prod")
126
  model = get_model_for_task("rag_lesson")
127
+ assert "deepseek-v4-pro" in model
128
 
129
  @patch.dict(os.environ, {"INFERENCE_ENFORCE_LOCK_MODEL": "false"})
130
  def test_returns_profile_default_for_chat(self):
131
  set_runtime_model_profile("prod")
132
  model = get_model_for_task("chat")
133
+ assert "deepseek-flash" in model
134
 
135
  @patch.dict(os.environ, {"INFERENCE_ENFORCE_LOCK_MODEL": "false"})
136
  def test_returns_runtime_override_for_chat(self):
 
142
  def test_enforce_qwen_overrides_task(self):
143
  set_runtime_model_profile("prod")
144
  model = get_model_for_task("rag_lesson")
145
+ assert "deepseek-flash" in model
146
 
147
 
148
  class TestIsSequentialModel:
 
154
  reset_runtime_overrides()
155
 
156
  def test_reasoner_is_sequential(self):
157
+ assert is_sequential_model("deepseek-v4-pro") is True
158
 
159
  def test_chat_is_not_sequential(self):
160
+ assert is_sequential_model("deepseek-flash") is False
161
 
162
  def test_empty_string_checks_env(self):
163
  result = is_sequential_model("")
164
  assert result is True or result is False
165
 
166
+ @patch.dict(os.environ, {"INFERENCE_MODEL_ID": "deepseek-v4-pro"})
167
  def test_env_model_reasoner_is_sequential(self):
168
  assert is_sequential_model("") is True
169
 
170
+ @patch.dict(os.environ, {"INFERENCE_MODEL_ID": "deepseek-flash"})
171
  def test_env_model_chat_is_not_sequential(self):
172
  assert is_sequential_model("") is False
173
 
 
175
  class TestModelSupportsThinking:
176
 
177
  def test_reasoner_supports_thinking(self):
178
+ assert model_supports_thinking("deepseek-v4-pro") is True
179
 
180
  def test_chat_does_not_support_thinking(self):
181
+ assert model_supports_thinking("deepseek-flash") is False
182
 
183
  def test_unknown_does_not_support_thinking(self):
184
  assert model_supports_thinking("meta-llama/Llama-3.1-8B-Instruct") is False
tests/test_perf_backend_runtime.py CHANGED
@@ -44,7 +44,7 @@ def _call_with_max_retries(max_retries: int | None) -> int:
44
  inference.ds_api_key = "mock-key-for-testing"
45
  request = InferenceRequest(
46
  messages=[{"role": "user", "content": "hi"}],
47
- model="deepseek-chat",
48
  task_type="chat",
49
  max_retries=max_retries,
50
  )
@@ -98,9 +98,9 @@ def _routing_table() -> dict:
98
  def test_routing_chat_verification_uses_chat_model_and_lessons_keep_reasoner():
99
  config = _routing_table()
100
  task_models = config["routing"]["task_model_map"]
101
- assert task_models["verify_solution"] == "deepseek-chat"
102
- assert task_models["rag_lesson"] == "deepseek-reasoner"
103
- assert task_models["risk_narrative"] == "deepseek-reasoner"
104
  assert "verify_solution" not in config["models"]["rag_primary"]["enable_thinking_tasks"]
105
 
106
 
 
44
  inference.ds_api_key = "mock-key-for-testing"
45
  request = InferenceRequest(
46
  messages=[{"role": "user", "content": "hi"}],
47
+ model="deepseek-flash",
48
  task_type="chat",
49
  max_retries=max_retries,
50
  )
 
98
  def test_routing_chat_verification_uses_chat_model_and_lessons_keep_reasoner():
99
  config = _routing_table()
100
  task_models = config["routing"]["task_model_map"]
101
+ assert task_models["verify_solution"] == "deepseek-flash"
102
+ assert task_models["rag_lesson"] == "deepseek-v4-pro"
103
+ assert task_models["risk_narrative"] == "deepseek-v4-pro"
104
  assert "verify_solution" not in config["models"]["rag_primary"]["enable_thinking_tasks"]
105
 
106
 
tests/test_practice_model_routing.py CHANGED
@@ -26,7 +26,7 @@ class TestPracticeRouting:
26
  """practice_generation and quiz_generation are distinct task types."""
27
  practice_model = get_model_for_task("practice_generation")
28
  quiz_model = get_model_for_task("quiz_generation")
29
- # Both route to deepseek-chat but via separate config keys
30
  # The important thing is they map through different env vars
31
  assert "deepseek" in practice_model.lower()
32
  assert "deepseek" in quiz_model.lower()
 
26
  """practice_generation and quiz_generation are distinct task types."""
27
  practice_model = get_model_for_task("practice_generation")
28
  quiz_model = get_model_for_task("quiz_generation")
29
+ # Both route to deepseek-flash but via separate config keys
30
  # The important thing is they map through different env vars
31
  assert "deepseek" in practice_model.lower()
32
  assert "deepseek" in quiz_model.lower()
tests/test_rag_event_loop.py CHANGED
@@ -93,7 +93,7 @@ def test_health_answers_while_a_rag_lesson_is_blocked_in_retrieval_and_inference
93
  ), patch("routes.rag_routes.retrieve_lesson_pdf_context", _blocking_retrieval), patch(
94
  "routes.rag_routes._get_inference_client", return_value=_BlockingInferenceClient()
95
  ), patch("routes.rag_routes._stream_reasoner_lesson", _blocking_reasoner_stream), patch(
96
- "routes.rag_routes._lesson_primary_model", return_value="deepseek-reasoner"
97
  ), patch("routes.rag_routes.verify_lesson_factuality", _verified), patch(
98
  "routes.rag_routes._fetch_youtube_videos", return_value=[]
99
  ), patch("routes.rag_routes._log_rag_usage", return_value=None):
 
93
  ), patch("routes.rag_routes.retrieve_lesson_pdf_context", _blocking_retrieval), patch(
94
  "routes.rag_routes._get_inference_client", return_value=_BlockingInferenceClient()
95
  ), patch("routes.rag_routes._stream_reasoner_lesson", _blocking_reasoner_stream), patch(
96
+ "routes.rag_routes._lesson_primary_model", return_value="deepseek-v4-pro"
97
  ), patch("routes.rag_routes.verify_lesson_factuality", _verified), patch(
98
  "routes.rag_routes._fetch_youtube_videos", return_value=[]
99
  ), patch("routes.rag_routes._log_rag_usage", return_value=None):
tests/test_rag_lesson_stream.py CHANGED
@@ -20,7 +20,7 @@ os.environ.setdefault("DEEPSEEK_API_KEY", "mock-key-for-testing")
20
 
21
  from routes import rag_routes # noqa: E402
22
 
23
- REASONER = "deepseek-reasoner"
24
  CHUNKS = [
25
  {
26
  "content": "A rational function is a quotient of two polynomial functions.",
@@ -605,7 +605,9 @@ def test_fallback_contract_reasoner_stream_request_shape(monkeypatch: pytest.Mon
605
  assert text == '{"sections": []}'
606
  assert fake.options == {"max_retries": 0}
607
  assert fake.create_kwargs["stream"] is True
608
- assert fake.create_kwargs["max_tokens"] == 8192
 
 
609
  assert fake.create_kwargs["model"] == REASONER
610
  assert "temperature" not in fake.create_kwargs and "top_p" not in fake.create_kwargs
611
  timeout = fake.create_kwargs["timeout"]
 
20
 
21
  from routes import rag_routes # noqa: E402
22
 
23
+ REASONER = "deepseek-v4-pro"
24
  CHUNKS = [
25
  {
26
  "content": "A rational function is a quotient of two polynomial functions.",
 
605
  assert text == '{"sections": []}'
606
  assert fake.options == {"max_retries": 0}
607
  assert fake.create_kwargs["stream"] is True
608
+ assert fake.create_kwargs["max_tokens"] == rag_routes._REASONER_LESSON_MAX_TOKENS
609
+ assert fake.create_kwargs["extra_body"] == {"thinking": {"type": "enabled"}}
610
+ assert fake.create_kwargs["reasoning_effort"] == rag_routes._REASONER_LESSON_EFFORT == "low"
611
  assert fake.create_kwargs["model"] == REASONER
612
  assert "temperature" not in fake.create_kwargs and "top_p" not in fake.create_kwargs
613
  timeout = fake.create_kwargs["timeout"]
tests/test_rag_pipeline.py CHANGED
@@ -208,12 +208,12 @@ class TestBuildLessonQuery:
208
 
209
  class TestIsSequentialModel:
210
  def test_sequential_for_reasoner(self):
211
- with patch.dict(os.environ, {"INFERENCE_MODEL_ID": "deepseek-reasoner"}):
212
  from services.inference_client import is_sequential_model
213
  assert is_sequential_model() is True
214
 
215
  def test_not_sequential_for_chat(self):
216
- with patch.dict(os.environ, {"INFERENCE_MODEL_ID": "deepseek-chat"}):
217
  from services.inference_client import is_sequential_model
218
  assert is_sequential_model() is False
219
 
 
208
 
209
  class TestIsSequentialModel:
210
  def test_sequential_for_reasoner(self):
211
+ with patch.dict(os.environ, {"INFERENCE_MODEL_ID": "deepseek-v4-pro"}):
212
  from services.inference_client import is_sequential_model
213
  assert is_sequential_model() is True
214
 
215
  def test_not_sequential_for_chat(self):
216
+ with patch.dict(os.environ, {"INFERENCE_MODEL_ID": "deepseek-flash"}):
217
  from services.inference_client import is_sequential_model
218
  assert is_sequential_model() is False
219
 
tests/test_regression_ai_perf.py CHANGED
@@ -173,9 +173,9 @@ def test_config_guard_shared_deepseek_client_has_no_sdk_retries(monkeypatch):
173
 
174
  def test_config_guard_task_model_routing():
175
  task_models = yaml.safe_load(MODELS_YAML.read_text(encoding="utf-8"))["routing"]["task_model_map"]
176
- assert task_models["rag_lesson"] == "deepseek-reasoner", "lessons keep full reasoning depth (user requirement)"
177
- assert task_models["chat"] == "deepseek-chat", "chat prefers speed (user requirement)"
178
- assert task_models["verify_solution"] == "deepseek-chat", "chat verification prefers speed (user requirement)"
179
 
180
 
181
  # โ”€โ”€โ”€ 3. Retrieval guards โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
 
173
 
174
  def test_config_guard_task_model_routing():
175
  task_models = yaml.safe_load(MODELS_YAML.read_text(encoding="utf-8"))["routing"]["task_model_map"]
176
+ assert task_models["rag_lesson"] == "deepseek-v4-pro", "lessons keep full reasoning depth (user requirement)"
177
+ assert task_models["chat"] == "deepseek-flash", "chat prefers speed (user requirement)"
178
+ assert task_models["verify_solution"] == "deepseek-flash", "chat verification prefers speed (user requirement)"
179
 
180
 
181
  # โ”€โ”€โ”€ 3. Retrieval guards โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
tests/test_regression_rag_lesson.py CHANGED
@@ -23,7 +23,7 @@ os.environ.setdefault("DEEPSEEK_API_KEY", "mock-key-for-testing")
23
 
24
  from routes import rag_routes # noqa: E402
25
 
26
- REASONER = "deepseek-reasoner"
27
  REAL_STREAM_REASONER_LESSON = rag_routes._stream_reasoner_lesson
28
  SSE_FIXTURE = Path(__file__).resolve().parents[2] / "src" / "services" / "__tests__" / "fixtures" / "ragLessonStream.sse"
29
  CHUNKS = [
@@ -550,8 +550,8 @@ def test_config_guard_lesson_primary_model_is_reasoner_without_env(bare_model_en
550
  def test_config_guard_prod_profile_routes_lessons_to_the_rag_model(
551
  bare_model_env: None, monkeypatch: pytest.MonkeyPatch
552
  ) -> None:
553
- """The HF Space runs MODEL_PROFILE=prod, which exports INFERENCE_MODEL_ID=deepseek-chat (overriding every
554
- task in the inference client's map) and HF_RAG_MODEL_ID=deepseek-reasoner. Lessons must follow the RAG model."""
555
  monkeypatch.setenv("INFERENCE_MODEL_ID", rag_routes.CHAT_MODEL)
556
  monkeypatch.setenv("HF_RAG_MODEL_ID", REASONER)
557
  assert rag_routes._lesson_primary_model() == REASONER
 
23
 
24
  from routes import rag_routes # noqa: E402
25
 
26
+ REASONER = "deepseek-v4-pro"
27
  REAL_STREAM_REASONER_LESSON = rag_routes._stream_reasoner_lesson
28
  SSE_FIXTURE = Path(__file__).resolve().parents[2] / "src" / "services" / "__tests__" / "fixtures" / "ragLessonStream.sse"
29
  CHUNKS = [
 
550
  def test_config_guard_prod_profile_routes_lessons_to_the_rag_model(
551
  bare_model_env: None, monkeypatch: pytest.MonkeyPatch
552
  ) -> None:
553
+ """The HF Space runs MODEL_PROFILE=prod, which exports INFERENCE_MODEL_ID=deepseek-flash (overriding every
554
+ task in the inference client's map) and HF_RAG_MODEL_ID=deepseek-v4-pro. Lessons must follow the RAG model."""
555
  monkeypatch.setenv("INFERENCE_MODEL_ID", rag_routes.CHAT_MODEL)
556
  monkeypatch.setenv("HF_RAG_MODEL_ID", REASONER)
557
  assert rag_routes._lesson_primary_model() == REASONER
tests/test_teacher_materials.py CHANGED
@@ -116,7 +116,7 @@ def mock_deepseek_success():
116
  ],
117
  "aiSafety": {
118
  "requiresGrounding": True,
119
- "allowedModels": ["deepseek-chat"],
120
  "groundingSources": ["teacher_file", "deped_rag"],
121
  },
122
  }
 
116
  ],
117
  "aiSafety": {
118
  "requiresGrounding": True,
119
+ "allowedModels": ["deepseek-flash"],
120
  "groundingSources": ["teacher_file", "deped_rag"],
121
  },
122
  }