repo stringclasses 454
values | file_path stringlengths 5 201 | extension stringclasses 1
value | content stringlengths 8 509k | num_lines int64 3 16.9k | size_bytes int64 8 511k |
|---|---|---|---|---|---|
DeepTutor | deeptutor/api/routers/notebook.py | .py | """
Notebook API Router
Provides notebook creation, querying, updating, deletion, and record management functions
"""
import json
from typing import AsyncGenerator, Literal
from fastapi import APIRouter, HTTPException
from fastapi.responses import StreamingResponse
from pydantic import BaseModel
from deeptutor.agent... | 359 | 10,278 |
DeepTutor | deeptutor/api/routers/settings.py | .py | """
Settings API Router
===================
UI preferences, configuration catalog management, and detailed streamed tests.
"""
from __future__ import annotations
import asyncio
import json
import logging
import time
from typing import Any, List, Literal, Optional
from fastapi import APIRouter, HTTPException, Reques... | 1,421 | 52,293 |
DeepTutor | deeptutor/api/routers/question.py | .py | import asyncio
import base64
from datetime import datetime
import logging
from pathlib import Path
import re
import sys
import traceback
from fastapi import APIRouter, WebSocket, WebSocketDisconnect
from deeptutor.agents.question import AgentCoordinator
from deeptutor.api.utils.task_id_manager import TaskIDManager
fr... | 571 | 22,058 |
DeepTutor | deeptutor/api/routers/personas.py | .py | """
Personas API Router
===================
CRUD endpoints for user-authored PERSONA.md files stored under
``data/user/workspace/personas/<name>/PERSONA.md``.
Personas are behaviour/voice presets, not capability skills: admin-authored
personas are visible to every user as read-only deployment presets (no grant
mechan... | 139 | 4,533 |
DeepTutor | deeptutor/api/routers/imports.py | .py | """
Import chat histories from external coding CLIs (Claude Code, Codex) into the
user's learning space as normal, re-openable sessions.
Reading the user's local ``~/.claude`` / ``~/.codex`` happens in the browser
(File System Access API) — those files live on the user's machine, not the
server. The browser normalizes... | 147 | 5,411 |
DeepTutor | deeptutor/api/routers/outputs.py | .py | """Request-scoped delivery of generated output artifacts."""
from __future__ import annotations
from pathlib import Path
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.responses import FileResponse
from deeptutor.api.routers.auth import require_auth
from deeptutor.multi_user.context impo... | 48 | 1,840 |
DeepTutor | deeptutor/api/routers/tools.py | .py | """
Tools API Router
================
Read-only listing of the chat agent's built-in tools, used by the Settings UI
to render the "Tools" sub-page. Returns each tool's definition (name,
description, parameters) alongside its bilingual prompt hints, so the frontend
can show authoritative copy without duplicating the ca... | 223 | 7,420 |
DeepTutor | deeptutor/api/routers/co_writer.py | .py | import asyncio
from datetime import datetime
import json
import logging
import re
import traceback
from typing import AsyncGenerator, Literal
import uuid
from fastapi import APIRouter, HTTPException
from fastapi.responses import StreamingResponse
from pydantic import BaseModel, Field
from deeptutor.co_writer.edit_age... | 619 | 20,529 |
DeepTutor | deeptutor/api/routers/attachments.py | .py | """HTTP endpoint for chat attachment downloads / previews.
The chat turn runtime persists every uploaded attachment to the
:class:`~deeptutor.services.storage.AttachmentStore` and records the public
URL on the message. The frontend preview drawer loads files via this
router, which only serves paths the store hands bac... | 92 | 3,524 |
DeepTutor | deeptutor/api/routers/partners.py | .py | """Partners management API.
A partner is an IM-connected companion driven by the chat agent loop.
This router owns: partner CRUD + lifecycle, the soul library, channel
config (schema-driven), asset provisioning (KB / skills / notebooks copied
into the partner workspace), tool configuration, history, and the web chat
e... | 1,179 | 44,638 |
DeepTutor | deeptutor/api/routers/memory.py | .py | """Memory v3 API — workbench backend.
Three layers, three modes (update / audit / dedup). Long-running work
is owned by the :mod:`runs` manager so a refresh / nav-away does not
kill it; clients re-attach by polling ``/runs/{id}/events?since=N``.
- ``GET /overview`` → all 11 docs' state +... | 786 | 26,319 |
DeepTutor | deeptutor/api/routers/unified_ws.py | .py | """
Unified WebSocket Endpoint
==========================
Single ``/api/v1/ws`` endpoint for turn-based execution and replayable streaming.
Supported client message ``type`` values:
- ``message`` / ``start_turn`` — start a new turn from a payload.
- ``subscribe_turn`` — stream events of an existing turn (with ``afte... | 326 | 14,144 |
DeepTutor | deeptutor/api/utils/tool_options.py | .py | """Configurable-tool surface shared by the partners and multi-user admin APIs.
``tools`` mirrors the user-toggleable system tools (the same pool the chat
composer / settings expose); ``builtin_tools`` lists the auto-mounted built-in
tools (rag / read_memory / web_fetch / …) a partner owner can selectively
allow or den... | 108 | 4,339 |
DeepTutor | deeptutor/api/utils/progress_broadcaster.py | .py | """
Progress Broadcaster - Manages WebSocket broadcasting of knowledge base progress
"""
import asyncio
import logging
from typing import Optional
from fastapi import WebSocket
logger = logging.getLogger(__name__)
class ProgressBroadcaster:
"""Manages WebSocket broadcasting of knowledge base progress"""
_... | 74 | 2,734 |
DeepTutor | deeptutor/api/utils/task_log_stream.py | .py | import asyncio
from collections import deque
from collections.abc import AsyncGenerator
import contextlib
import importlib
import json
import logging
import threading
import time
from typing import Any
from deeptutor.logging import (
ProcessLogEvent,
bind_log_context,
capture_process_logs,
current_log_... | 336 | 13,178 |
DeepTutor | deeptutor/api/utils/task_id_manager.py | .py | """
Task ID Manager - Assigns unique IDs to each background task
"""
from datetime import datetime, timedelta
import logging
import threading
from typing import Optional
import uuid
logger = logging.getLogger(__name__)
class TaskIDManager:
"""Singleton class for managing task IDs"""
_MAX_COMPLETED_TASKS = ... | 121 | 4,515 |
DeepTutor | deeptutor/utils/archive_extractor.py | .py | """Safe extraction of user-uploaded ZIP archives.
A naive ``ZipFile.extractall`` is unsafe for untrusted uploads: it is
vulnerable to *Zip Slip* (path traversal via ``../`` or absolute member
names), *zip bombs* (tiny archives that decompress to fill the disk), and it
happily writes any file type. This module extracts... | 198 | 7,600 |
DeepTutor | deeptutor/utils/error_rate_tracker.py | .py | """
Error Rate Tracker - Track error rates per provider with alerting.
"""
from collections import defaultdict, deque
import logging
import threading
import time
from typing import Callable, Dict, Optional
logger = logging.getLogger(__name__)
class ErrorRateTracker:
"""
Tracks error rates per provider with ... | 112 | 3,942 |
DeepTutor | deeptutor/utils/config_manager.py | .py | import os
from pathlib import Path
import tempfile
from threading import RLock
from typing import Any, Dict, List, Optional
import yaml
from ..services.config.loader import get_runtime_settings_dir
class ConfigManager:
"""
Minimal runtime YAML manager for `data/user/settings/main.yaml`.
The long-lived ... | 130 | 5,091 |
DeepTutor | deeptutor/utils/document_validator.py | .py | #!/usr/bin/env python
"""
Document Validator - Validation utilities for document uploads
"""
import mimetypes
import os
import re
from typing import ClassVar
import unicodedata
class DocumentValidator:
"""Document validation utilities"""
# Maximum file size in bytes (200MB), applied uniformly to every forma... | 171 | 5,526 |
DeepTutor | deeptutor/utils/json_parser.py | .py | #!/usr/bin/env python
"""
Robust JSON parsing utilities with automatic repair and markdown extraction.
Provides safe JSON parsing that handles:
- Markdown code block wrapping (```json...```)
- Malformed JSON (missing commas, trailing commas, etc.)
- Unescaped newlines and control characters
- Empty responses
"""
impo... | 202 | 7,138 |
DeepTutor | deeptutor/utils/document_extractor.py | .py | """Document text extraction for chat attachments.
Bytes-in, text-out. Used by the chat turn runtime to inline the text of
user-dropped files into the ``effective_user_message`` sent to the LLM.
Two format families:
* **Binary Office** (.pdf / .docx / .xlsx / .pptx) — parsed with pymupdf /
python-docx / openpyxl... | 705 | 24,384 |
DeepTutor | deeptutor/utils/error_utils.py | .py | #!/usr/bin/env python
"""
Error Utilities - Error formatting and handling utilities
"""
import json
from typing import Optional
def _find_json_block(message: str) -> Optional[str]:
"""Extract potential JSON block from message by matching braces."""
start_idx = message.find("{")
if start_idx == -1:
... | 82 | 2,238 |
DeepTutor | deeptutor/utils/network/circuit_breaker.py | .py | """
Circuit Breaker - Simple circuit breaker for providers.
"""
import logging
import threading
import time
from typing import Dict
logger = logging.getLogger(__name__)
class CircuitBreaker:
"""
Simple circuit breaker that opens when error rate is high.
"""
def __init__(self, failure_threshold: int... | 89 | 3,085 |
DeepTutor | deeptutor/logging/formatters.py | .py | """Formatters for DeepTutor's stdlib logging pipeline."""
from __future__ import annotations
from datetime import datetime, timezone
import json
import logging
from typing import Any
from .context import LOG_CONTEXT_FIELDS, current_log_context
class ContextFilter(logging.Filter):
"""Attach contextvars and expl... | 50 | 1,766 |
DeepTutor | deeptutor/logging/process_stream.py | .py | """Process-log event capture for user-visible operational logs."""
from __future__ import annotations
import asyncio
from collections.abc import Callable, Iterator
from contextlib import contextmanager
from dataclasses import dataclass, field
import inspect
import logging
from typing import Any
from .context import ... | 109 | 3,194 |
DeepTutor | deeptutor/logging/__init__.py | .py | """DeepTutor Logging 2.0: stdlib core plus structured process-log events."""
from .config import LoggingConfig, get_default_log_dir, get_global_log_level, load_logging_config
from .configure import configure_logging
from .context import LOG_CONTEXT_FIELDS, bind_log_context, current_log_context
from .process_stream imp... | 26 | 809 |
DeepTutor | deeptutor/logging/configure.py | .py | """DeepTutor logging bootstrap."""
from __future__ import annotations
import logging
from logging.handlers import RotatingFileHandler
from pathlib import Path
import sys
from .config import LoggingConfig, load_logging_config
from .formatters import ConsoleFormatter, ContextFilter, JsonlFormatter
from .loguru_bridge ... | 78 | 2,293 |
DeepTutor | deeptutor/logging/context.py | .py | """Request-scoped logging context."""
from __future__ import annotations
from collections.abc import Iterator
from contextlib import contextmanager
import contextvars
from typing import Any
LOG_CONTEXT_FIELDS = (
"request_id",
"turn_id",
"session_id",
"task_id",
"capability",
"stage",
"si... | 40 | 1,002 |
DeepTutor | deeptutor/logging/loguru_bridge.py | .py | """Bridge optional loguru records into stdlib logging."""
from __future__ import annotations
import logging
from typing import Any
def install_loguru_bridge(level: int = logging.DEBUG) -> bool:
"""Forward loguru logs to stdlib if loguru is installed."""
try:
from loguru import logger as loguru_logge... | 29 | 797 |
DeepTutor | deeptutor/logging/config.py | .py | """Logging configuration loaded from runtime settings."""
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
@dataclass(frozen=True)
class LoggingConfig:
level: str = "INFO"
console_output: bool = True
file_output: bool = True
log_dir: str | None = None
... | 50 | 1,565 |
DeepTutor | deeptutor/logging/adapters/__init__.py | .py | """
Log Adapters
============
Adapters for forwarding logs from external libraries to the unified logging system.
"""
from .llamaindex import LlamaIndexLogContext, LlamaIndexLogForwarder
__all__ = [
"LlamaIndexLogContext",
"LlamaIndexLogForwarder",
]
| 14 | 262 |
DeepTutor | deeptutor/logging/adapters/llamaindex.py | .py | #!/usr/bin/env python
"""Scoped LlamaIndex stdlib logging configuration."""
from __future__ import annotations
from contextlib import contextmanager
import logging
from typing import Any, Iterator
class LlamaIndexLogForwarder(logging.Handler):
"""Forward selected LlamaIndex records into a DeepTutor logger."""
... | 75 | 2,637 |
DeepTutor | deeptutor/logging/stats/llm_stats.py | .py | """
LLM Stats Tracker
=================
Simple utility for tracking LLM token usage and costs across all modules.
Outputs summary via the unified logging system.
Usage:
from deeptutor.logging import LLMStats
stats = LLMStats("Solver")
# After each LLM call:
stats.add_call(
model="gpt-4o-mini... | 194 | 6,111 |
DeepTutor | deeptutor/logging/stats/__init__.py | .py | """
Statistics Tracking
===================
Utilities for tracking LLM usage, costs, and performance metrics.
"""
from .llm_stats import MODEL_PRICING, LLMCall, LLMStats, estimate_tokens, get_pricing
__all__ = [
"LLMStats",
"LLMCall",
"get_pricing",
"estimate_tokens",
"MODEL_PRICING",
]
| 17 | 311 |
DeepTutor | deeptutor/learning/storage.py | .py | from __future__ import annotations
import json
from pathlib import Path
import threading
import time
from deeptutor.learning.models import LearningProgress
from deeptutor.services.file_io import atomic_write_text as _atomic_write_text
from deeptutor.services.path_service import get_path_service
# Module-level lock s... | 56 | 1,942 |
DeepTutor | deeptutor/learning/models.py | .py | from __future__ import annotations
from enum import Enum
import time
from typing import Any, Literal
from pydantic import BaseModel, ConfigDict, Field
_KNOWLEDGE_TYPE_LEGACY: dict[str, str] = {
"记忆型": "memory",
"概念型": "concept",
"程序型": "procedure",
"设计型": "design",
}
_ERROR_TYPE_LEGACY: dict[str, st... | 231 | 6,819 |
DeepTutor | deeptutor/learning/scheduler.py | .py | from __future__ import annotations
import os
import time
from deeptutor.learning.models import (
KnowledgeType,
LearningProgress,
RepetitionState,
ReviewTask,
)
INTERVAL_SEQUENCES: dict[KnowledgeType, list[int]] = {
KnowledgeType.MEMORY: [0, 1, 3, 7, 14, 30, 60],
KnowledgeType.CONCEPT: [3, 7,... | 102 | 3,505 |
DeepTutor | deeptutor/learning/policy.py | .py | """Mastery Path policy — pure decisions over a :class:`LearningProgress`.
No LLM calls, no I/O. This is the engine the chat-loop tutor consults each
turn. It answers three questions:
* **is this objective mastered?** (:func:`is_mastered` — a HARD, per-type gate)
* **what should the learner work on next?** (:func:`nex... | 296 | 11,710 |
DeepTutor | deeptutor/learning/pending.py | .py | """Public, stable views of pending mastery questions.
The persisted :class:`~deeptutor.learning.models.PendingQuestion` contains the
server-only expected answer. This module projects it into the smaller contract
that is safe to give to the tutor model and interactive clients. It also owns
the pure multiple-choice tran... | 167 | 5,598 |
DeepTutor | deeptutor/learning/__init__.py | .py | """Mastery Path — structured mastery-based learning engine.
Modules:
models — Pydantic data models
storage — JSON persistence
scheduler — Spaced repetition
mastery — Mastery scoring policy (swappable)
grading — Deterministic answer grading
service — Business logic
pro... | 42 | 906 |
DeepTutor | deeptutor/learning/mastery.py | .py | """Mastery scoring policy — intentionally simple and swappable.
``compute_mastery`` maps a knowledge point's attempt history to a 0..1 mastery
score. The current policy is a recency-weighted accuracy with a low-confidence
cap: a single lucky answer cannot "master" a point — mastery is capped until
there is enough evid... | 41 | 1,552 |
DeepTutor | deeptutor/learning/service.py | .py | from __future__ import annotations
import logging
import time
from typing import TYPE_CHECKING
import uuid
from deeptutor.learning.grading import classify_error, grade_answer
from deeptutor.learning.mastery import compute_mastery
from deeptutor.learning.models import (
ErrorRecord,
LearningModule,
Learnin... | 296 | 12,382 |
DeepTutor | deeptutor/learning/prompts.py | .py | """Mastery Path LLM prompt templates.
The prompt text lives in ``deeptutor/learning/prompts/{en,zh}.yaml`` so the
capability and API can follow the active UI language. The module-level constants
remain as the Chinese defaults for older tests/imports.
"""
from __future__ import annotations
from functools import lru_c... | 102 | 3,705 |
DeepTutor | deeptutor/learning/grading.py | .py | """Deterministic answer grading + coarse error classification for Mastery Path."""
from __future__ import annotations
from difflib import SequenceMatcher
import re
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from deeptutor.learning.models import ErrorType
def grade_answer(user_answer: str, expected_answ... | 65 | 1,982 |
DeepTutor | deeptutor/learning/tests/test_prompt_language_fallback.py | .py | """Mastery Path prompts must not fall back to Chinese for every other language.
Only ``en.yaml`` and ``zh.yaml`` exist, and the old candidate list was
``[lang, "zh" if lang != "zh" else "en"]`` — so a Japanese learner got Chinese
prompt scaffolding while the rest of the book stayed Japanese (issue #712).
"""
from __f... | 52 | 1,734 |
DeepTutor | deeptutor/learning/tests/test_policy.py | .py | """Tests for the Mastery Path policy — the per-type gate and the gate-driven
"what's next" decision that replaced the old linear stage march.
These assert the two Alpha-style principles the old engine violated:
* a HARD gate — an objective is not mastered (and never advanced past) until
its evidence clears the thre... | 212 | 7,710 |
DeepTutor | deeptutor/learning/tests/test_scheduler.py | .py | import time
import pytest
from deeptutor.learning.models import (
ErrorRecord,
ErrorType,
KnowledgeType,
LearningProgress,
RepetitionState,
ReviewTask,
)
from deeptutor.learning.scheduler import INTERVAL_SEQUENCES, SpacedRepetitionScheduler
@pytest.fixture
def scheduler():
return SpacedR... | 282 | 11,016 |
DeepTutor | deeptutor/learning/tests/test_storage.py | .py | from pathlib import Path
import time
import pytest
from deeptutor.learning.models import KnowledgeType, LearningProgress, RepetitionState
from deeptutor.learning.storage import LearningStore, _atomic_write_text
@pytest.fixture
def store(tmp_path):
return LearningStore(root=tmp_path)
# ── save / load ─────────... | 201 | 7,670 |
DeepTutor | deeptutor/learning/tests/test_mastery_tools.py | .py | """Tests for the Mastery Path tools — the seam between the chat-loop tutor and
the engine. They drive the full loop the tutor uses: build a path, read the
gate, pose + grade questions, assess qualitative objectives, with the active
path id injected server-side (never by the model)."""
from __future__ import annotation... | 579 | 19,688 |
DeepTutor | deeptutor/learning/tests/test_guided_mastery_updates.py | .py | """Tests for Mastery Path mastery updates from graded answers.
The unified post-answer pipeline is ``LearningService.grade_and_record``: it
grades one answer, recomputes mastery (recency-weighted with a low-confidence
cap), advances the spaced-repetition state, rebuilds the review queue, and
persists. The mastery tool... | 283 | 10,016 |
DeepTutor | deeptutor/learning/tests/test_models.py | .py | import time
from deeptutor.learning.models import (
DiagnosticResult,
ErrorRecord,
ErrorType,
KnowledgePoint,
KnowledgeType,
LearningModule,
LearningProgress,
LearningStage,
PendingQuestion,
QuizAttempt,
RepetitionState,
RetryAttempt,
ReviewTask,
)
# ── Enums ──────... | 305 | 11,378 |
DeepTutor | deeptutor/learning/tests/test_mastery_choices.py | .py | """Unit tests for the choice-question data contract
(:mod:`deeptutor.capabilities.mastery.choices`).
These exercise the pure option-handling rules in isolation — parsing, body
validation, answer normalisation, and legacy recovery — independent of the
tool/engine wiring that :mod:`test_mastery_tools` drives end to end.... | 186 | 6,028 |
DeepTutor | deeptutor/learning/tests/test_grading.py | .py | """Tests for the grading module and the unified post-answer pipeline.
``grade_answer`` is the pure correctness check. ``classify_error`` is the
coarse wrong-answer tagger. ``LearningService.grade_and_record`` folds both of
those through the full record -> mastery -> spaced-repetition pipeline and is
fail-closed: with ... | 249 | 9,296 |
DeepTutor | deeptutor/learning/tests/test_api_endpoints.py | .py | """API endpoint tests for the mastery_path router."""
import json
from unittest.mock import AsyncMock, patch
from fastapi import FastAPI
from fastapi.testclient import TestClient
import pytest
from deeptutor.api.routers.mastery_path import router
from deeptutor.learning.storage import LearningStore
@pytest.fixture... | 553 | 20,651 |
DeepTutor | deeptutor/learning/tests/test_service_replace_merge.py | .py | """Tests for the unified LearningService pipeline.
Covers module replacement (replace_modules / init_modules both have replace
semantics and purge stale per-KP state), the recency-weighted mastery policy
with its low-confidence cap, and the fail-closed grade_and_record pipeline that
records an attempt, recomputes mast... | 413 | 16,290 |
DeepTutor | deeptutor/book/storage.py | .py | """
Book Storage
============
Per-book directory + per-page file persistence with atomic writes.
Layout (relative to ``data/user/workspace/book/``)::
book_{book_id}/
├── manifest.json # Book metadata
├── spine.json # Spine
├── progress.json # Progress
├── inputs.json # Captured B... | 265 | 10,643 |
DeepTutor | deeptutor/book/models.py | .py | """
Book Engine data models
=======================
Pydantic models that describe the persistent state of a Book:
- ``BookInputs`` snapshot of the four sources captured at creation.
- ``BookProposal`` LLM-generated proposal (Stage 1 output).
- ``Spine`` / ``Chapter`` chapter tree (Stage 2 output).
- ``Page`` / ``Bloc... | 475 | 18,535 |
DeepTutor | deeptutor/book/__init__.py | .py | """
Book Engine
===========
Independent runtime engine that compiles user inputs (chat history, notebooks,
knowledge bases, intent) into structured, block-based, interactive "living
books". Sits parallel to ``ChatOrchestrator`` and reuses the existing
``ToolRegistry`` / ``CapabilityRegistry`` / ``StreamBus`` plumbing.... | 43 | 812 |
DeepTutor | deeptutor/book/engine.py | .py | """
BookEngine
==========
Top-level orchestrator for the Book Engine. Sits **parallel** to
``ChatOrchestrator`` (i.e. it is **not** a ``BaseCapability``) and is the
single public entry point used by the API router, CLI, and SDK.
Lifecycle
---------
::
create_book(...) → BookProposal (Stage 1, requ... | 1,298 | 51,407 |
DeepTutor | deeptutor/book/context.py | .py | """Utilities for turning selected book pages into chat context.
The chat runtime consumes this module from two places:
* the main chat page when a user picks pages via ``@book``;
* the book reader side panel, which automatically references the current page.
Keep this module pure and storage-backed only. It should no... | 433 | 14,946 |
DeepTutor | deeptutor/book/kb_health.py | .py | """KB drift detection & log.md health checks for the Book Engine.
This module is intentionally side-effect-free: it inspects the on-disk
representation of a knowledge base (the ``raw/`` documents folder) to derive a
deterministic fingerprint, compares it to the fingerprint snapshot stored on
the Book manifest, and sur... | 309 | 11,662 |
DeepTutor | deeptutor/book/compiler.py | .py | """
BookCompiler
============
Drives the per-page block-generation pipeline.
Responsibilities
----------------
1. Plan a page (call :class:`PagePlanner`) if it has no blocks yet.
2. For each block, look up the right :class:`BlockGenerator` and run it.
3. Persist the page after every block (atomic incremental progress... | 369 | 12,638 |
DeepTutor | deeptutor/book/inputs.py | .py | """
BookInputs Fusion
=================
Merges the four input sources (user intent, chat history, notebook references,
knowledge bases) into a structured ``IdeationContext`` text block consumed by
``IdeationAgent``.
Reuses:
- ``deeptutor.services.session.get_sqlite_session_store`` for chat history
- ``deeptutor.servi... | 363 | 13,241 |
DeepTutor | deeptutor/book/streaming.py | .py | """
Book Engine streaming helpers
=============================
Thin wrapper around ``StreamBus`` that fixes ``source="book_engine"`` and
defines book-specific event metadata schemas.
"""
from __future__ import annotations
from contextlib import asynccontextmanager
from typing import Any
from deeptutor.core.stream ... | 135 | 3,931 |
DeepTutor | deeptutor/book/blocks/animation.py | .py | """Animation block – Manim-rendered math animation.
Calls :class:`deeptutor.agents.math_animator.pipeline.MathAnimatorPipeline`
to generate a video clip explaining the chapter. The payload exposes the
rendered artifact URL(s) plus a short summary.
This block requires the optional ``math-animator`` extras (LaTeX, ffmp... | 124 | 4,813 |
DeepTutor | deeptutor/book/blocks/section.py | .py | """
Section block generator
=======================
Long-form section block (1500-2500 words) introduced in BookEngine v2.
Generation is a *two-pass* pipeline:
1. **Outline pass** — single LLM call returns a JSON ``{intro, subsections,
key_takeaway}`` plan. ``subsections`` is a list of
``{heading, role, focus,... | 351 | 13,373 |
DeepTutor | deeptutor/book/blocks/_llm_writer.py | .py | """
Shared LLM helper for text-flavoured block generators.
Avoids subclassing BaseAgent for these tiny calls; instead uses
``deeptutor.services.llm.complete`` directly with a sane default config.
"""
from __future__ import annotations
import json
from typing import Any
from deeptutor.services.llm import (
clean... | 190 | 6,891 |
DeepTutor | deeptutor/book/blocks/concept_graph.py | .py | """Concept-graph block — deterministically rendered from the spine's graph.
This generator never calls an LLM. It reads ``ctx.extra['concept_graph']`` (a
``ConceptGraph`` model dump injected by the engine) and emits both:
- A Mermaid ``graph TD`` source the frontend can render with its existing
Mermaid pipeline.
- ... | 134 | 4,792 |
DeepTutor | deeptutor/book/blocks/callout.py | .py | """Callout block – key idea / common pitfall / summary highlight.
Prompts live in ``deeptutor/book/prompts/{en,zh}/callout.yaml``.
"""
from __future__ import annotations
from typing import Any
from ..models import BlockType, SourceAnchor
from ._llm_writer import llm_text
from ._prompts import get_book_prompt, load_... | 62 | 2,061 |
DeepTutor | deeptutor/book/blocks/_language.py | .py | """Backward-compatible re-export of shared prompt language helpers."""
from deeptutor.services.prompt.language import (
append_language_directive,
language_directive,
language_label,
normalize_language,
)
__all__ = [
"append_language_directive",
"language_directive",
"language_label",
... | 16 | 344 |
DeepTutor | deeptutor/book/blocks/timeline.py | .py | """Timeline block – LLM-generated chronological events list.
Phase 2 implementation. Returns a structured list of events the frontend
renders as a vertical timeline.
Prompts live in ``deeptutor/book/prompts/{en,zh}/timeline.yaml``.
"""
from __future__ import annotations
from typing import Any
from ..models import ... | 66 | 2,350 |
DeepTutor | deeptutor/book/blocks/__init__.py | .py | """Block generators – one per ``BlockType``."""
# Phase 2+ generators
from .animation import AnimationGenerator
from .base import (
BlockContext,
BlockGenerator,
BlockGeneratorRegistry,
GenerationFailure,
get_block_registry,
)
from .callout import CalloutGenerator
from .code import CodeGenerator
fr... | 42 | 1,087 |
DeepTutor | deeptutor/book/blocks/figure.py | .py | """Figure block – static visual figure (svg / chartjs / mermaid).
Wraps :class:`deeptutor.agents.visualize.pipeline.VisualizePipeline` with
``render_mode="figure"`` so the LLM picks the best static rendering for the
chapter, but never falls back to interactive HTML (handled by the
``interactive`` block type).
Like th... | 122 | 4,699 |
DeepTutor | deeptutor/book/blocks/_rag_helpers.py | .py | """
Optional RAG lookup helper for block generators.
If the block context has a primary KB and ``rag_enabled``, run a single
``rag_search`` call and return both the synthesised text and a list of
``SourceAnchor`` objects. Failures are swallowed silently – RAG is treated as
"nice to have" by every generator.
"""
from ... | 111 | 3,539 |
DeepTutor | deeptutor/book/blocks/flash_cards.py | .py | """Flash-cards block – LLM-generated study cards.
Returns ``cards: [{front, back, hint}]`` ready for the frontend
``FlashCardsBlock`` component.
Prompts live in ``deeptutor/book/prompts/{en,zh}/flash_cards.yaml``.
"""
from __future__ import annotations
from typing import Any
from ..models import BlockType, SourceA... | 74 | 2,748 |
DeepTutor | deeptutor/book/blocks/code.py | .py | """Code block – generates a runnable code snippet plus brief explanation.
Phase 2 implementation. Uses the unified LLM service with a strict JSON
response. The frontend ``CodeBlock`` component renders the code and the
explanation side-by-side; the playground "code_execution" tool can be
hooked in later for live runs.
... | 69 | 2,596 |
DeepTutor | deeptutor/book/blocks/text.py | .py | """Text block generator – Markdown body.
Also exposes :func:`generate_bridge_text` so the compiler can attach a short
1-2 sentence transition to *any* block's payload (not as a separate block).
Prompts live in ``deeptutor/book/prompts/{en,zh}/text.yaml``.
"""
from __future__ import annotations
from typing import An... | 114 | 3,825 |
DeepTutor | deeptutor/book/blocks/user_note.py | .py | """User note block – passthrough; user-authored content has no LLM step."""
from __future__ import annotations
from typing import Any
from ..models import BlockType, SourceAnchor
from .base import BlockContext, BlockGenerator
class UserNoteGenerator(BlockGenerator):
block_type = BlockType.USER_NOTE
async ... | 27 | 685 |
DeepTutor | deeptutor/book/blocks/deep_dive.py | .py | """Deep-dive block – Phase 3 implementation.
Renders a "Go deeper" call-to-action card. The actual sub-page is created on
demand by the BookEngine (``create_deep_dive_subpage``) when the user clicks
the card; we only emit suggested topics here so the page reader can render
the affordance.
Prompts live in ``deeptutor/... | 70 | 2,561 |
DeepTutor | deeptutor/book/blocks/_prompts.py | .py | """
Shared prompt loader for non-BaseAgent call sites in ``deeptutor/book``.
All LLM-facing prompts inside this module live as YAML under
``deeptutor/book/prompts/{en,zh}/<name>.yaml`` and are loaded through the
unified :class:`~deeptutor.services.prompt.PromptManager`. This helper is the
thin wrapper that block gener... | 68 | 2,354 |
DeepTutor | deeptutor/book/blocks/interactive.py | .py | """Interactive block – self-contained interactive HTML widget.
Wraps :class:`deeptutor.agents.visualize.pipeline.VisualizePipeline` with
``render_mode="html"``. The payload carries an HTML document the frontend
renders in an isolated iframe.
The draft is checked by the deterministic local ``validate_visualization``.
... | 101 | 3,837 |
DeepTutor | deeptutor/book/blocks/base.py | .py | """
BlockGenerator base class
=========================
A BlockGenerator turns a ``Block`` (with ``params``) plus some shared context
(book / chapter / page / KB) into a populated ``Block`` (``payload`` filled,
``status`` set to READY/ERROR).
Generators are stateless and are looked up by ``BlockType`` via
``get_block... | 233 | 7,236 |
DeepTutor | deeptutor/book/blocks/quiz.py | .py | """Quiz block – delegates to the existing question generation coordinator."""
from __future__ import annotations
import logging
from typing import Any
from ..models import BlockType, SourceAnchor
from .base import BlockContext, BlockGenerator, GenerationFailure
logger = logging.getLogger(__name__)
class QuizGener... | 96 | 3,654 |
DeepTutor | deeptutor/book/agents/source_explorer.py | .py | """
SourceExplorer
==============
Stage 2 prep of the BookEngine pipeline.
Given the user's confirmed ``BookProposal`` plus the four-source ``BookInputs``
snapshot, ``SourceExplorer`` performs a *parallel multi-query sweep* over the
attached knowledge bases and additional sources (notebook records, recent chat
histor... | 505 | 18,499 |
DeepTutor | deeptutor/book/agents/page_planner.py | .py | """
Section Architect (formerly PagePlanner)
========================================
Stage 3 of the BookEngine pipeline. Translate a ``Chapter`` into a concrete
ordered list of ``Block`` shells (type + params + dependencies) ready for the
``BookCompiler`` to fill in.
BookEngine v2 architecture
----------------------... | 365 | 14,811 |
DeepTutor | deeptutor/book/agents/spine_agent.py | .py | """
SpineAgent
==========
Stage 2 of the BookEngine pipeline. Given an approved ``BookProposal`` and
optional source material from the learner's knowledge bases, produce a
``Spine`` of chapters that the user can review and edit before compilation.
"""
from __future__ import annotations
from typing import Any
from d... | 185 | 6,270 |
DeepTutor | deeptutor/book/agents/__init__.py | .py | """BookEngine agents: Ideation, SourceExplorer, Spine, PagePlanner."""
from .ideation_agent import IdeationAgent
from .page_planner import PagePlanner
from .source_explorer import SourceExplorer
from .spine_agent import SpineAgent
from .spine_synthesizer import SpineSynthesizer
__all__ = [
"IdeationAgent",
"S... | 16 | 399 |
DeepTutor | deeptutor/book/agents/spine_synthesizer.py | .py | """
SpineSynthesizer
================
Stage 2 of the BookEngine pipeline (replaces the legacy ``SpineAgent``).
Implements a multi-round **Draft → Critique → Revise** reasoning loop driven
by an ``ExplorationReport`` produced by ``SourceExplorer``. The synthesiser
emits *both* a chapter ``Spine`` AND a directed ``Conc... | 791 | 29,444 |
DeepTutor | deeptutor/book/agents/ideation_agent.py | .py | """
IdeationAgent
=============
Stage 1 of the BookEngine pipeline: turn an ``IdeationContext`` into a
``BookProposal`` that the user can confirm or edit before Spine generation.
"""
from __future__ import annotations
from typing import Any
from deeptutor.agents.base_agent import BaseAgent
from deeptutor.utils.json... | 97 | 3,126 |
DeepTutor | deeptutor/runtime/launcher.py | .py | """Local Web launcher for the installed DeepTutor app."""
from __future__ import annotations
import atexit
from dataclasses import dataclass
import hashlib
import json
import os
from pathlib import Path
import shutil
import signal
import socket
import subprocess
import sys
import threading
import time
from typing imp... | 1,161 | 39,982 |
DeepTutor | deeptutor/runtime/home.py | .py | """Runtime home resolution for installed and source DeepTutor runs."""
from __future__ import annotations
import os
from pathlib import Path
DEEPTUTOR_HOME_ENV = "DEEPTUTOR_HOME"
PACKAGE_ROOT = Path(__file__).resolve().parents[2]
def get_runtime_home(home: str | Path | None = None) -> Path:
"""Return the direc... | 42 | 1,063 |
DeepTutor | deeptutor/runtime/__init__.py | .py | """Runtime orchestration and registry helpers."""
from .mode import RunMode, get_mode, is_cli, is_server, set_mode
from .orchestrator import ChatOrchestrator
__all__ = [
"ChatOrchestrator",
"RunMode",
"get_mode",
"is_cli",
"is_server",
"set_mode",
]
| 14 | 276 |
DeepTutor | deeptutor/runtime/memory_reclaim.py | .py | """Best-effort memory reclamation after infrequent, allocation-heavy jobs."""
from __future__ import annotations
import asyncio
import gc
import logging
import sys
import threading
from typing import Any
logger = logging.getLogger(__name__)
_reclaim_tasks: dict[asyncio.AbstractEventLoop, asyncio.Task[tuple[int, bool... | 74 | 2,274 |
DeepTutor | deeptutor/runtime/memory_probe.py | .py | """Resident-memory snapshot of the running DeepTutor process tree.
The counterpart to :mod:`deeptutor.runtime.memory_reclaim`: that module *acts*
on memory (cycle collection, ``malloc_trim``), this one *observes* it so the
settings status strip can show what the app actually costs.
Two things make "how much memory do... | 344 | 11,885 |
DeepTutor | deeptutor/runtime/mode.py | .py | """
Run Mode
========
Controls whether DeepTutor is running as a CLI application or an API server.
Modules can check the mode to conditionally import server-only dependencies.
"""
from enum import Enum
import os
class RunMode(str, Enum):
CLI = "cli"
SERVER = "server"
_current_mode: RunMode | None = None
... | 48 | 985 |
DeepTutor | deeptutor/runtime/banner.py | .py | """Branded banner + localized labels for ``deeptutor start`` / ``deeptutor init``.
Both commands read the user's language preference from
``data/user/settings/interface.json`` (default ``en``) so their startup
output matches the UI language the user has chosen.
"""
from __future__ import annotations
from rich.align ... | 321 | 15,304 |
DeepTutor | deeptutor/runtime/request_contracts.py | .py | """Public request contracts and config validators for built-in capabilities."""
from __future__ import annotations
from typing import Any, Callable, Literal
from pydantic import BaseModel, ConfigDict, Field, ValidationError
from deeptutor.agents.math_animator.request_config import (
MathAnimatorRequestConfig,
... | 178 | 6,053 |
DeepTutor | deeptutor/runtime/orchestrator.py | .py | """
Chat Orchestrator
=================
Unified entry point that routes user messages to the appropriate capability.
All consumers (CLI, WebSocket, SDK) call the orchestrator.
"""
from __future__ import annotations
import asyncio
import logging
from typing import Any, AsyncIterator
import uuid
from deeptutor.core.c... | 147 | 5,113 |
DeepTutor | deeptutor/runtime/bootstrap/builtin_capabilities.py | .py | """Built-in capability class paths."""
BUILTIN_CAPABILITY_CLASSES: dict[str, str] = {
"chat": "deeptutor.agents.chat.capability:ChatCapability",
"deep_solve": "deeptutor.capabilities.solve.capability:DeepSolveCapability",
"deep_question": "deeptutor.agents.question.capability:DeepQuestionCapability",
"... | 12 | 655 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.