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/services/embedding/adapters/dashscope_native.py
.py
"""Aliyun DashScope embedding adapter (text + multimodal). Uses the ``dashscope`` Python SDK rather than the OpenAI contract because DashScope's native API shape does not match it. DashScope splits embeddings across two surfaces served from different endpoints, and the SDK derives the endpoint from the model id: * mu...
243
9,264
DeepTutor
deeptutor/services/embedding/adapters/openai_sdk.py
.py
"""Legacy embedding adapter using AsyncOpenAI. Public Settings providers use exact endpoint URLs and raw HTTP adapters so the URL shown in Settings is the URL sent on the wire. This SDK adapter is retained for old configs/tests that intentionally depend on AsyncOpenAI semantics. """ from __future__ import annotations...
156
5,485
DeepTutor
deeptutor/services/embedding/adapters/openai_compatible.py
.py
"""OpenAI-compatible embedding adapter for OpenAI, Azure, HuggingFace, LM Studio, etc.""" import json import logging from typing import Any, Dict import httpx from deeptutor.services.llm.openai_http_client import disable_ssl_verify_enabled from .base import ( BaseEmbeddingAdapter, EmbeddingProviderError, ...
345
14,973
DeepTutor
deeptutor/services/embedding/adapters/jina.py
.py
"""Jina AI embedding adapter with task-aware embeddings and late chunking.""" import logging from typing import Any, Dict import httpx from deeptutor.services.llm.openai_http_client import disable_ssl_verify_enabled from .base import BaseEmbeddingAdapter, EmbeddingRequest, EmbeddingResponse logger = logging.getLog...
154
5,768
DeepTutor
deeptutor/services/embedding/adapters/ollama.py
.py
"""Ollama Embedding Adapter for local embeddings.""" import logging from typing import Any, Dict from urllib.parse import urljoin, urlparse import httpx from deeptutor.services.llm.openai_http_client import disable_ssl_verify_enabled from .base import BaseEmbeddingAdapter, EmbeddingRequest, EmbeddingResponse logge...
146
5,304
DeepTutor
deeptutor/services/embedding/adapters/cohere.py
.py
"""Cohere Embedding Adapter for v1 and v2 API.""" import logging from typing import Any, Dict import httpx from deeptutor.services.llm.openai_http_client import disable_ssl_verify_enabled from .base import BaseEmbeddingAdapter, EmbeddingRequest, EmbeddingResponse logger = logging.getLogger(__name__) class Cohere...
177
6,715
DeepTutor
deeptutor/services/embedding/adapters/base.py
.py
""" Base Embedding Adapter ======================= Abstract base class for all embedding adapters. Defines the contract that all embedding providers must implement. """ from abc import ABC, abstractmethod from dataclasses import dataclass from typing import Any, Dict, List, Optional def looks_like_multimodal_embedd...
191
6,939
DeepTutor
deeptutor/services/parsing/types.py
.py
"""Canonical, engine-agnostic document-parse result (the bridge IR). The parse layer sits between *input material* and its consumers (question extraction, RAG indexing, future LightRAG). Every engine — MinerU, Docling, markitdown — produces the same :class:`ParsedDocument` so consumers never branch on which engine ran...
53
1,949
DeepTutor
deeptutor/services/parsing/__init__.py
.py
"""Shared, engine-pluggable document-parsing layer (the "bridge"). Sits between input material and its consumers (question extraction, RAG indexing, future LightRAG): one canonical IR (:class:`ParsedDocument`), one content-addressed cache, a registry of pluggable engines (text-only, MinerU, Docling, markitdown). Parsi...
35
1,052
DeepTutor
deeptutor/services/parsing/signature.py
.py
"""Stable identity of a parse configuration. Mirrors :class:`~deeptutor.services.rag.index_versioning.EmbeddingSignature`: only the fields that change the produced artifact go into the hash, so re-parsing the same bytes with the same config hits cache, while a backend/version/knob change yields a fresh signature dir a...
51
1,775
DeepTutor
deeptutor/services/parsing/service.py
.py
"""ParseService — the public entry to the document-parse bridge. Resolves the active (or requested) engine, computes the content-addressed cache key, returns a cached :class:`ParsedDocument` on hit, and on miss runs the engine behind the model-download readiness gate, then caches and returns the IR. Consumption is pul...
144
5,155
DeepTutor
deeptutor/services/parsing/cache.py
.py
"""Content-addressed parse cache + canonical IR loader. The cache is keyed by ``(source_hash, parser_signature)`` and shared across all consumers (question extraction, RAG indexing). Re-parsing the same bytes with the same engine config is a directory lookup; a different engine/version/knob lands in a different signat...
193
6,822
DeepTutor
deeptutor/services/parsing/base.py
.py
"""Structural contract every document-parsing engine implements. Parsing is deliberately kept OFF the ``RAGPipeline`` protocol (``services/rag/pipelines/base.py``): it is an upstream, shared, *optional* stage. An engine turns bytes/path into a :class:`~deeptutor.services.parsing.types.ParsedDocument` and declares its ...
80
2,730
DeepTutor
deeptutor/services/parsing/engines/__init__.py
.py
"""Pluggable document-parsing engines. Each engine implements the :class:`~deeptutor.services.parsing.base.Parser` contract and is selected by name through :mod:`deeptutor.services.parsing.engines.factory`. Third-party imports are lazy so an engine whose dependency is absent simply reports ``is_available() is False`` ...
8
352
DeepTutor
deeptutor/services/parsing/engines/_versions.py
.py
"""Cheap, cached package-version lookup for parser signatures. Using the installed distribution version (not a CLI ``--version`` subprocess) keeps signature computation cheap while still invalidating the parse cache when an engine is upgraded. """ from __future__ import annotations from functools import lru_cache im...
23
539
DeepTutor
deeptutor/services/parsing/engines/factory.py
.py
"""Parser engine registry. Maps an engine name to its adapter class, mirroring the RAG pipeline factory (``services/rag/factory.py``). Engine modules import their third-party deps lazily, so importing this registry is cheap and never fails on a missing optional dependency. """ from __future__ import annotations from...
168
5,065
DeepTutor
deeptutor/services/parsing/engines/_install.py
.py
"""One-click background jobs for optional parser engines. The Document Parsing settings page runs two kinds of background job without the user dropping to a shell: * **install** — ``pip install`` an engine's optional PyPI package. * **models** — download an engine's model weights (e.g. Docling's layout/table model...
270
9,741
DeepTutor
deeptutor/services/parsing/engines/docling/__init__.py
.py
"""Docling engine — structured document conversion (downloads local models). Converts PDF/Office/HTML/images into a structured document and exports Markdown. Downloads layout/table models on first run, so it shares the same ``allow_local_model_download`` gate as MinerU local. """
7
284
DeepTutor
deeptutor/services/parsing/engines/docling/engine.py
.py
"""Docling engine adapter implementing the ``Parser`` protocol. Docling's structured conversion is exported to Markdown for the canonical IR. Structured ``content_list`` mapping is intentionally deferred — markdown is a valid IR (consumers fall back to it), and a faithful block mapping depends on the Docling document ...
161
5,820
DeepTutor
deeptutor/services/parsing/engines/docling/config.py
.py
"""Docling engine config (read-side adapter over the v2 settings slice).""" from __future__ import annotations from dataclasses import dataclass from deeptutor.services.config.runtime_settings import ( DOCUMENT_PARSING_ENGINE_DOCLING, load_document_parsing_settings, ) @dataclass(frozen=True) class DoclingC...
34
1,036
DeepTutor
deeptutor/services/parsing/engines/text_only/__init__.py
.py
"""Built-in text-only parsing engine. This is the default, dependency-light path: it reuses DeepTutor's legacy text extractors and emits markdown/plain text for downstream RAG providers. """ from .engine import TextOnlyParser __all__ = ["TextOnlyParser"]
10
258
DeepTutor
deeptutor/services/parsing/engines/text_only/engine.py
.py
"""Text-only parser adapter implementing the ``Parser`` protocol.""" from __future__ import annotations from pathlib import Path from typing import Any, Callable, Optional from deeptutor.utils.document_extractor import ( SUPPORTED_DOC_EXTENSIONS, DocumentExtractionError, extract_text_from_path, ) from de...
68
1,936
DeepTutor
deeptutor/services/parsing/engines/mineru/cloud.py
.py
"""MinerU cloud (mineru.net) v4 API backend. Implements the token-required *Precision API* flow for a single local PDF: 1. ``POST /api/v4/file-urls/batch`` → ``{batch_id, file_urls: [signed_url]}`` 2. ``PUT`` the raw PDF bytes to ``signed_url`` (no auth, no Content-Type) 3. Poll ``GET /api/v4/extract-results/batch/{b...
344
13,635
DeepTutor
deeptutor/services/parsing/engines/mineru/models.py
.py
"""One-click MinerU model download. Wraps the ``mineru-models-download`` CLI (MinerU 2.x) in a background job the settings UI can start, poll, and cancel. The same source/endpoint settings also feed the parse subprocess via :func:`model_env_overrides`, so a lazy first-parse download honors the configured mirror even w...
214
7,857
DeepTutor
deeptutor/services/parsing/engines/mineru/__init__.py
.py
"""MinerU parsing engine (local CLI or hosted cloud API). Modules: * ``config`` — :class:`MinerUConfig` + ``resolve_mineru_config`` (read-side adapter over ``document_parsing.json``). * ``backend`` — ``parse_pdf_to_workdir`` (local/cloud dispatch) + CLI probes. * ``local`` — the local MinerU CLI subprocess runne...
14
624
DeepTutor
deeptutor/services/parsing/engines/mineru/engine.py
.py
"""MinerU engine adapter implementing the ``Parser`` protocol. Thin wrapper over the existing ``parse_pdf_to_workdir`` (local CLI / cloud dispatch). The readiness gate (``readiness.py``) enforces "no silent model download" before a local parse runs. """ from __future__ import annotations from pathlib import Path fro...
73
2,357
DeepTutor
deeptutor/services/parsing/engines/mineru/config.py
.py
"""Resolved MinerU backend configuration. This is the single read-side adapter between the persisted ``document_parsing.json`` settings (owned by :class:`RuntimeSettingsService`) and the MinerU parser backend in this package. ``load_mineru_settings`` returns the MinerU engine slice of the v2 document-parsing structure...
93
3,782
DeepTutor
deeptutor/services/parsing/engines/mineru/local.py
.py
#!/usr/bin/env python """ Parse PDF files using MinerU and save results to reference_papers directory """ import argparse from collections import deque from collections.abc import Callable import os from pathlib import Path import shutil import subprocess import sys import time # Minimum seconds between on_output cal...
263
8,699
DeepTutor
deeptutor/services/parsing/engines/mineru/backend.py
.py
"""Unified MinerU parsing entrypoint. Hides the local-CLI vs cloud-API split behind one function so callers (the mimic-mode adapter) never branch on backend. Both branches converge on the same contract: write MinerU artifacts into a working directory and return its path. Backend selection comes from ``document_parsing...
172
6,515
DeepTutor
deeptutor/services/parsing/engines/mineru/readiness.py
.py
"""MinerU model-readiness probe — the "no silent download" gate. The MinerU CLI auto-downloads multi-GB model weights on first local parse, and DeepTutor cannot stop the CLI itself from doing so. So the gate lives one level up: a local parse is only allowed to start when models are already present *or* the user explic...
96
3,441
DeepTutor
deeptutor/services/parsing/engines/markitdown/__init__.py
.py
"""Microsoft markitdown engine — lightweight, no model downloads. Converts a wide range of formats (Office, PDF, HTML, CSV, EPub, images, …) to Markdown. Pure-Python; the zero-download default engine. Produces ``markdown`` only (no structured ``content_list``). """
7
271
DeepTutor
deeptutor/services/parsing/engines/markitdown/engine.py
.py
"""markitdown engine adapter implementing the ``Parser`` protocol.""" from __future__ import annotations import importlib.util from pathlib import Path from typing import Callable, Optional from ...base import ReadinessReport from ...signature import ParserSignature from ...types import ParserError from .._versions ...
97
2,824
DeepTutor
deeptutor/services/parsing/engines/markitdown/config.py
.py
"""markitdown engine config (read-side adapter over the v2 settings slice).""" from __future__ import annotations from dataclasses import dataclass from deeptutor.services.config.runtime_settings import ( DOCUMENT_PARSING_ENGINE_MARKITDOWN, load_document_parsing_settings, ) @dataclass(frozen=True) class Ma...
32
923
DeepTutor
deeptutor/services/parsing/engines/pymupdf4llm/__init__.py
.py
"""PyMuPDF4LLM engine — lightweight, pure-Python, image-capable. Converts PDF / e-book formats to Markdown via PyMuPDF (fitz). No model downloads and no CUDA, so it runs on low-end / GPU-less machines. Unlike the text-only and markitdown engines it can also extract embedded images and rendered vector graphics into the...
9
413
DeepTutor
deeptutor/services/parsing/engines/pymupdf4llm/engine.py
.py
"""PyMuPDF4LLM engine adapter implementing the ``Parser`` protocol. A lightweight, pure-Python PDF/e-book → Markdown engine built on PyMuPDF (fitz): no CUDA, no model weights, suited to low-end / GPU-less machines. Unlike the text-only and markitdown engines it can also extract embedded images and rendered vector grap...
154
5,867
DeepTutor
deeptutor/services/parsing/engines/pymupdf4llm/config.py
.py
"""PyMuPDF4LLM engine config (read-side adapter over the v2 settings slice).""" from __future__ import annotations from dataclasses import dataclass from deeptutor.services.config.runtime_settings import ( DOCUMENT_PARSING_ENGINE_PYMUPDF4LLM, load_document_parsing_settings, ) @dataclass(frozen=True) class ...
37
1,111
DeepTutor
deeptutor/services/parsing/engines/liteparse/__init__.py
.py
"""liteparse document-parsing engine adapter.""" from __future__ import annotations from .engine import LiteParseParser __all__ = ["LiteParseParser"]
8
153
DeepTutor
deeptutor/services/parsing/engines/liteparse/engine.py
.py
"""LiteParse engine adapter implementing the ``Parser`` protocol. LiteParse (run-llama/liteparse) is a Rust-backed PDF/Office/image parser: no model weights, no CUDA, in-process. Like the PyMuPDF4LLM engine it can extract embedded images, so it follows the same workdir contract — one ``<stem>.md`` plus an ``images/`` ...
146
5,555
DeepTutor
deeptutor/services/parsing/engines/liteparse/config.py
.py
"""liteparse engine config (read-side adapter over the v2 settings slice).""" from __future__ import annotations from dataclasses import dataclass from deeptutor.services.config.runtime_settings import ( DOCUMENT_PARSING_ENGINE_LITEPARSE, LITEPARSE_IMAGE_MODES, load_document_parsing_settings, ) @datacl...
66
2,196
DeepTutor
deeptutor/services/partners/workspace.py
.py
"""Partner workspace layout + asset provisioning. The partner workspace is a verbatim clone of the chat user-workspace format (``PathService`` layout), so the chat agent loop's tools read it natively: data/partners/<id>/workspace/ ← synthetic scope root ├── knowledge_bases/<kb>/ ← copied...
389
14,559
DeepTutor
deeptutor/services/partners/scope.py
.py
"""Synthetic user scope for partner runtimes. A partner is executed as a *synthetic user*: its workspace (``data/partners/<id>/workspace``) is laid out exactly like a chat user workspace, and every service that resolves paths through ``get_current_path_service()`` (rag, skills, notebooks, memory, task workspaces) tran...
54
1,510
DeepTutor
deeptutor/services/partners/runtime.py
.py
"""Partner agent runtime — drives the chat agent loop from IM messages. This replaces the deleted TutorBot engine. A partner has NO engine of its own: every inbound message becomes one chat turn executed by ``ChatOrchestrator`` → ``AgenticChatPipeline`` (the exact loop the product chat uses), run inside the partner's ...
736
31,746
DeepTutor
deeptutor/services/partners/manager.py
.py
"""Partner Manager — create / start / stop / manage in-process partners. Each partner runs as a set of asyncio tasks within the DeepTutor server process: a ``PartnerRunner`` (chat-agent-loop driver), an outbound message router, and one listener task per enabled IM channel. Every partner owns an isolated chat-format wo...
1,334
54,875
DeepTutor
deeptutor/services/partners/__init__.py
.py
"""Partner services — lifecycle, runtime, workspace, and sessions.""" from deeptutor.services.partners.manager import ( PartnerConfig, PartnerInstance, PartnerManager, get_partner_manager, mask_channel_secrets, slugify_partner_id, slugify_soul_id, ) from deeptutor.services.partners.runtime ...
26
645
DeepTutor
deeptutor/services/partners/model_runtime.py
.py
"""Helpers for resolving per-partner LLM model selection.""" from __future__ import annotations from typing import Any from deeptutor.services.llm.config import LLMConfig from deeptutor.services.model_selection import LLMSelection from deeptutor.services.model_selection.runtime import resolve_llm_config_for_selectio...
37
1,428
DeepTutor
deeptutor/services/partners/sessions.py
.py
"""Lightweight JSONL conversation store for partner sessions. One JSONL file per session key (``telegram:12345``, ``web:<session_id>``, ``partner:<id>`` …) under ``data/partners/<id>/sessions/``. This is the partner-side replacement for the deleted engine's SessionManager: it only has to hand the chat agent loop an Op...
318
12,591
DeepTutor
deeptutor/services/partners/commands.py
.py
"""Slash commands for partner chat surfaces.""" from __future__ import annotations from dataclasses import dataclass import shlex from typing import Any, Callable from deeptutor.agents._shared.tool_composition import default_optional_tools from deeptutor.partners.bus.events import InboundMessage from deeptutor.servi...
273
10,691
DeepTutor
deeptutor/knowledge/manifest.py
.py
"""Document inventory of a knowledge base — the facts retrieval cannot answer. Retrieval answers "what does the material say". It cannot answer "how many files are in this knowledge base", "did I upload X", or "list what's in here": those are questions about the KB's *inventory*, and no amount of passage similarity pr...
430
16,910
DeepTutor
deeptutor/knowledge/manager.py
.py
#!/usr/bin/env python """ Knowledge Base Manager Manages multiple knowledge bases and provides utilities for accessing them. """ from contextlib import contextmanager from datetime import datetime, timedelta import hashlib import json import logging import os from pathlib import Path import shutil import stat import ...
1,862
74,793
DeepTutor
deeptutor/knowledge/initializer.py
.py
#!/usr/bin/env python """Knowledge base initialization through the selected RAG provider.""" from __future__ import annotations import argparse import asyncio from datetime import datetime import json import logging from pathlib import Path import shutil from typing import Optional from deeptutor.knowledge.naming im...
349
12,452
DeepTutor
deeptutor/knowledge/__init__.py
.py
#!/usr/bin/env python """Knowledge base package exports (lazy-loaded).""" from __future__ import annotations from typing import Any __all__ = [ "DocumentAdder", "KnowledgeBaseInitializer", "KnowledgeBaseManager", ] def __getattr__(name: str) -> Any: if name == "DocumentAdder": from .add_doc...
29
721
DeepTutor
deeptutor/knowledge/kb_types.py
.py
"""Knowledge-base kind discriminators. A KB entry's ``type`` field tells the rest of the system how to treat it. Most KBs are the default *indexed* kind (chunk → embed → retrieve via an RAG provider) and carry no ``type``. *Connected* KBs are pointers: their content lives outside ``data/knowledge_bases`` and we never ...
127
5,917
DeepTutor
deeptutor/knowledge/progress_tracker.py
.py
""" Progress Tracker - Tracks knowledge base initialization progress """ import asyncio from collections.abc import Callable from datetime import datetime from enum import Enum import json import logging from pathlib import Path from deeptutor.services.file_io import atomic_write_json # Use unified logging system _...
245
8,810
DeepTutor
deeptutor/knowledge/add_documents.py
.py
#!/usr/bin/env python """Incrementally add documents to an existing knowledge base.""" from __future__ import annotations import argparse import asyncio from dataclasses import dataclass from datetime import datetime import hashlib import json import logging from pathlib import Path import shutil from typing import L...
481
17,604
DeepTutor
deeptutor/knowledge/naming.py
.py
"""Knowledge-base name validation helpers.""" from __future__ import annotations import re import unicodedata _CONTROL_CHARS = re.compile(r"[\x00-\x1f\x7f]") _FORBIDDEN_CHARS = set('<>:"/\\|?*#%') _MAX_KB_NAME_LENGTH = 120 def validate_knowledge_base_name(name: str) -> str: """Validate and normalize a user-fac...
41
1,460
DeepTutor
deeptutor/config/constants.py
.py
#!/usr/bin/env python """ Constants for DeepTutor """ from pathlib import Path # Project root directory - central location for all path calculations PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent # Valid tools for investigate agent VALID_INVESTIGATE_TOOLS = ["rag", "web_search", "none"] # Valid tools ...
31
562
DeepTutor
deeptutor/config/accessors.py
.py
from typing import Callable class ConfigAccessor: def __init__(self, loader: Callable[[], dict]): self._loader = loader def llm_model(self) -> str: cfg = self._loader() return str(cfg.get("llm", {}).get("model", "Pro/Flash")) def llm_provider(self) -> str: cfg = self._loa...
19
534
DeepTutor
deeptutor/config/defaults.py
.py
""" Default configuration values for DeepTutor. """ from deeptutor.runtime.home import get_runtime_home _project_root = get_runtime_home() # Default configuration DEFAULTS = { "llm": {"model": "gpt-4o-mini", "provider": "openai"}, "paths": { "user_data_dir": str(_project_root / "data" / "user"), ...
18
476
DeepTutor
deeptutor/config/schema.py
.py
from typing import Any, Dict from pydantic import BaseModel, field_validator class LLMConfig(BaseModel): model: str provider: str = "openai" class PathsConfig(BaseModel): user_data_dir: str knowledge_bases_dir: str user_log_dir: str class AppConfig(BaseModel): llm: LLMConfig paths: Pa...
39
832
DeepTutor
deeptutor/config/settings.py
.py
""" Configuration Settings for DeepTutor Environment Variables: LLM_RETRY__MAX_RETRIES: Maximum retry attempts for LLM calls (default: 3) LLM_RETRY__BASE_DELAY: Base delay between retries in seconds (default: 1.0) LLM_RETRY__EXPONENTIAL_BACKOFF: Whether to use exponential backoff (default: True) Examples:...
51
1,468
DeepTutor
deeptutor/core/capability_protocol.py
.py
""" Capability Protocol =================== Base class for the Capability layer (Level 2). Capabilities are multi-step agent pipelines invoked when the user selects a deep mode (e.g. Deep Solve, Deep Question). """ from __future__ import annotations from abc import ABC, abstractmethod from dataclasses import datacla...
69
1,940
DeepTutor
deeptutor/core/trace.py
.py
"""Trace helpers for rendering structured execution timelines in the UI.""" from __future__ import annotations from typing import Any from uuid import uuid4 def new_call_id(prefix: str = "call") -> str: """Generate a short stable-enough id for one visible trace card.""" return f"{prefix}-{uuid4().hex[:10]}"...
91
2,351
DeepTutor
deeptutor/core/errors.py
.py
""" Base exception classes for consistent error handling across the application. Provides a standardized way to distinguish between bugs, recoverable errors, and configuration issues. """ from typing import Any, Dict, Optional class DeepTutorError(Exception): """Base class for all application errors in DeepTutor...
58
1,311
DeepTutor
deeptutor/core/tool_protocol.py
.py
""" Tool Protocol ============= Base classes for the Tool layer (Level 1). Every tool — built-in or contributed via plugin — implements ``BaseTool``. """ from __future__ import annotations from abc import ABC, abstractmethod from dataclasses import dataclass, field from typing import Any, Protocol @dataclass class...
275
9,667
DeepTutor
deeptutor/core/i18n.py
.py
"""Small runtime i18n helper for backend-facing user messages.""" from __future__ import annotations from typing import Any def _parse_language(language: str | None) -> str: raw = (language or "en").strip().lower() if raw.startswith("zh") or raw in {"cn", "chinese"}: return "zh" return "en" _M...
134
7,250
DeepTutor
deeptutor/core/__init__.py
.py
"""Core contracts shared across runtime, tools, and capabilities.""" from .capability_protocol import BaseCapability, CapabilityManifest from .context import Attachment, UnifiedContext from .stream import StreamEvent, StreamEventType from .stream_bus import StreamBus from .tool_protocol import ( BaseTool, Tool...
35
834
DeepTutor
deeptutor/core/context.py
.py
""" Unified Context =============== A single data object that flows through the orchestrator into every tool / capability / plugin invocation. """ from __future__ import annotations from dataclasses import dataclass, field from typing import Any @dataclass class Attachment: """A file or image attached to the u...
85
3,645
DeepTutor
deeptutor/core/stream_bus.py
.py
""" Stream Bus ========== Async event channel that tools / capabilities emit into and consumers (CLI renderer, WebSocket pusher, JSON writer) read from. Usage:: bus = StreamBus() # Producer side (inside a capability) await bus.emit(StreamEvent(type=StreamEventType.CONTENT, content="Hello")) # Consu...
326
9,424
DeepTutor
deeptutor/core/stream.py
.py
""" Stream Event Protocol ===================== Defines the unified streaming event format used by all tools, capabilities, and plugins to communicate progress and results to consumers (CLI, WebSocket, SDK). """ from __future__ import annotations from dataclasses import dataclass, field from enum import Enum import ...
73
2,030
DeepTutor
deeptutor/core/agentic/labels.py
.py
r"""Protocol-label parsing for streaming LLM responses. The agentic engine drives LLM calls with a ``\`\`LABEL\`\`+content`` protocol: prompts require one allowed label, double-backtick-wrapped, on the first line of every reply, then the rest of the content. The parser detects that label up front, tolerates a few prov...
120
5,101
DeepTutor
deeptutor/core/agentic/labeled_step.py
.py
r"""One streaming LLM call with protocol-label routing. The core single-round-trip primitive. Given an OpenAI-compatible streaming client, optional tool schemas, and a label protocol, this: * Parses the first chunks for a ``\`\`LABEL\`\``` prefix. * For *non-final* labels (e.g. ``THINK``, ``TOOL``, ``REPLAN``), strea...
567
24,881
DeepTutor
deeptutor/core/agentic/__init__.py
.py
r"""Foundational agentic engine primitives. These modules implement the chat-style ``\`\`LABEL\`\`+content`` LLM protocol as reusable building blocks. Any capability that wants a streaming, label-driven LLM loop (chat, solve step, etc.) composes them. Layering: * :mod:`labels` — protocol-label parsing (param...
79
2,585
DeepTutor
deeptutor/core/agentic/tool_arg_guard.py
.py
"""Pre-dispatch validation of model-authored tool arguments. Under a large tool surface and a long history, models intermittently emit a native function call whose ``arguments`` is empty (or partial) even though the schema marks fields required — reproduced on several OpenAI-compatible providers (issue #779). Before ...
140
5,277
DeepTutor
deeptutor/core/agentic/usage.py
.py
"""Token-usage accumulator shared across LLM calls within a single turn.""" from __future__ import annotations import logging from typing import Any logger = logging.getLogger(__name__) class UsageTracker: """Accumulate prompt/completion tokens across many streaming LLM calls. Two ingestion paths: * ...
145
5,454
DeepTutor
deeptutor/core/agentic/messages.py
.py
"""Canonical message builders for agentic conversations.""" from __future__ import annotations from typing import Any def assistant_message_with_tool_calls( content: str, tool_calls: list[dict[str, Any]], ) -> dict[str, Any]: """Build the assistant message that precedes tool result messages.""" retu...
31
789
DeepTutor
deeptutor/core/agentic/client.py
.py
"""OpenAI-compatible client factory and completion kwargs. Lifted from chat's pipeline so any capability that wants a streaming LLM call with tools can construct the same client + kwargs without re-implementing provider gating, Azure detection, SSL bypass, or per-model token caps. """ from __future__ import annotatio...
502
17,753
DeepTutor
deeptutor/core/agentic/loop.py
.py
"""Label-driven iteration scheduler. The agentic loop drives a conversation with the LLM until one of the caller-declared *terminal labels* fires. Each iteration is one :func:`~deeptutor.core.agentic.labeled_step.run_labeled_step` call, after which the loop: * validates the protocol (one label, no inline duplicates, ...
445
17,580
DeepTutor
deeptutor/core/agentic/tool_dispatch.py
.py
"""Parallel tool-call dispatch with per-tool sub-traces. Lifted from chat's pipeline. Capability-agnostic: the caller supplies: * a ``KwargAugmenter`` — how to enrich the LLM-supplied tool args with server-side context (e.g. chat injects ``source_index`` for ``read_source``; solve will do the same for its own too...
674
27,059
DeepTutor
deeptutor/api/main.py
.py
from contextlib import asynccontextmanager import logging import sys from fastapi import Depends, FastAPI from fastapi.middleware.cors import CORSMiddleware from deeptutor.logging import configure_logging from deeptutor.services.config import ( ensure_runtime_settings_files, export_runtime_settings_to_env, ...
492
17,169
DeepTutor
deeptutor/api/run_server.py
.py
#!/usr/bin/env python """ Uvicorn Server Startup Script Uses Python API instead of command line to avoid Windows path parsing issues. """ import asyncio import os from pathlib import Path import sys from deeptutor.runtime.home import get_runtime_home # Windows: uvicorn defaults to SelectorEventLoop which does not su...
85
3,120
DeepTutor
deeptutor/api/routers/voice.py
.py
"""Voice endpoints — text-to-speech and speech-to-text. These are thin HTTP surfaces over :mod:`deeptutor.services.voice`. Config comes from the admin-managed model catalog (``services.tts`` / ``services.stt``), so voice is shared infrastructure like embedding/search — any authenticated user may call it; it is not gat...
131
4,620
DeepTutor
deeptutor/api/routers/agent_config.py
.py
#!/usr/bin/env python """ Agent Configuration API - Provides agent metadata for data-driven UI. """ from fastapi import APIRouter router = APIRouter() # Agent registry - single source of truth for agent UI metadata AGENT_REGISTRY = { "solve": { "icon": "HelpCircle", "color": "blue", "labe...
60
1,354
DeepTutor
deeptutor/api/routers/subagents.py
.py
"""Subagent connections API. Backs the "My Agents → connected agents" feature: detect which local agent CLIs (Claude Code, Codex, Gemini CLI, Kimi CLI, opencode, MiMo Code) are installed on this machine, connect one as a pointer KB the chat composer can select, and configure the consult budget. Connections are stored ...
326
13,103
DeepTutor
deeptutor/api/routers/knowledge.py
.py
""" Knowledge Base API Router ========================= Handles knowledge base CRUD operations, file uploads, and initialization. """ import asyncio from datetime import datetime import json import logging import mimetypes import os from pathlib import Path import re import shutil import traceback from uuid import uu...
2,963
114,904
DeepTutor
deeptutor/api/routers/book.py
.py
""" Book Engine API Router ====================== REST + WebSocket endpoints for the ``BookEngine``. Phase 1 surface: create / confirm / compile / read / delete + a per-book event stream. """ from __future__ import annotations import asyncio import logging from typing import Any from fastapi import APIRouter, HTTPE...
670
24,257
DeepTutor
deeptutor/api/routers/space_cli_apps.py
.py
""" CLI apps API ============ Mounted at ``/api/v1/space/cli-apps``. Two audiences on one surface, split by method rather than by route prefix so the page has one thing to read: * **anyone signed in** — ``GET /apps`` (what is installed, and whether I may use it), ``GET /catalog`` (what exists), ``PUT /apps/{id}/ena...
223
7,923
DeepTutor
deeptutor/api/routers/question_notebook.py
.py
""" Question Notebook API — persists quiz questions, bookmarks, and categories. """ from __future__ import annotations import base64 as _b64 import logging import uuid as _uuid from fastapi import APIRouter, HTTPException, Query, Response from pydantic import BaseModel, Field from deeptutor.services.session import ...
336
11,639
DeepTutor
deeptutor/api/routers/space_mcp.py
.py
""" Per-user MCP API ================ The servers an individual configures for themselves, mounted at ``/api/v1/space/mcp``. Auth-gated, **not** admin-gated: this is the whole point of the surface — a learner adds the hosted services they use without an administrator in the loop. What keeps that safe is narrow rather...
461
18,653
DeepTutor
deeptutor/api/routers/quiz_judge.py
.py
"""AI judge WebSocket — grades a learner's quiz answer. Mounted on its own (without router-level HTTP auth dependencies) because WebSocket upgrades cannot use FastAPI's HTTP dependency injection, so we rely on ``ws_require_auth`` inside the handler — mirroring the pattern used by ``unified_ws``. """ from __future__ i...
428
16,071
DeepTutor
deeptutor/api/routers/_partners_channel_schema.py
.py
"""Channel-schema introspection — bridges Pydantic channel configs to the Web UI. Used by ``GET /api/v1/partners/channels/schema`` so the front-end can render generic forms for ANY channel (built-in or plugin) without hard-coding fields. Why live here vs inside ``deeptutor.partners.channels``? * This is an API-shap...
177
6,627
DeepTutor
deeptutor/api/routers/chat.py
.py
""" Chat API Router ================ WebSocket endpoint for lightweight chat with session management. REST endpoints for session operations. """ import logging from fastapi import APIRouter, HTTPException, WebSocket, WebSocketDisconnect from deeptutor.agents.chat import ChatAgent, SessionManager from deeptutor.serv...
250
9,077
DeepTutor
deeptutor/api/routers/system.py
.py
""" System Status API Router Manages system status checks and model connection tests """ import asyncio from datetime import datetime import time from fastapi import APIRouter from pydantic import BaseModel from deeptutor.multi_user.context import get_current_user from deeptutor.runtime import memory_probe from deep...
382
14,097
DeepTutor
deeptutor/api/routers/dashboard.py
.py
"""Dashboard API backed by the unified SQLite session store.""" from typing import Any from fastapi import APIRouter, HTTPException from deeptutor.services.session import get_session_store router = APIRouter() @router.get("/recent") async def get_recent_activities(limit: int = 50, type: str | None = None): st...
62
2,217
DeepTutor
deeptutor/api/routers/sessions.py
.py
""" Unified session history API. """ from __future__ import annotations import logging from typing import Any from fastapi import APIRouter, HTTPException, Query from pydantic import BaseModel, Field, field_validator from deeptutor.services.session import get_session_store, get_sqlite_session_store from deeptutor.s...
231
8,377
DeepTutor
deeptutor/api/routers/mcp_settings.py
.py
""" MCP Settings API Router ======================= Manage the deployment-global MCP server registry: read/update the config, inspect live connection status, and probe a server before saving. Mounted at ``/api/v1/settings/mcp``. Admin-gated: the registry is deployment-global state, and a stdio server's ``command`` ru...
134
4,511
DeepTutor
deeptutor/api/routers/auth.py
.py
"""Auth router — login, logout, status, registration, profile, and user-management endpoints.""" from contextvars import Token as _CtxToken import logging import re from fastapi import ( APIRouter, Cookie, Depends, File, Header, HTTPException, Request, Response, UploadFile, Web...
872
30,400
DeepTutor
deeptutor/api/routers/mastery_path.py
.py
"""Guided Learning API Router.""" from __future__ import annotations import html import json from fastapi import APIRouter, HTTPException from pydantic import BaseModel from pydantic import ValidationError as PydanticValidationError from deeptutor.learning import policy as learning_policy from deeptutor.learning im...
309
11,109
DeepTutor
deeptutor/api/routers/skills.py
.py
""" Skills API Router ================= CRUD endpoints for user-authored SKILL.md files stored under ``data/user/workspace/skills/<name>/SKILL.md``. Mounted at ``/api/v1/skills``. """ from __future__ import annotations from fastapi import APIRouter, HTTPException from pydantic import BaseModel, Field from deeptuto...
306
10,757
DeepTutor
deeptutor/api/routers/plugins_api.py
.py
""" Plugins API Router ================== Lists registered tools, capabilities, and playground plugins. Provides direct tool execution for the Playground tester. """ import asyncio import contextlib import json import logging import re import time from typing import Any, AsyncGenerator from fastapi import APIRouter,...
433
14,327
DeepTutor
deeptutor/api/routers/capabilities_settings.py
.py
"""Capabilities settings endpoint. Surfaces the per-capability tunables (temperature, max_tokens, stage budgets, iteration limits) currently scattered across ``data/user/settings/agents.yaml`` and ``data/user/settings/main.yaml``. Mirrors the pattern used by ``/api/v1/memory/settings``: * ``GET /settings`` → retur...
39
1,189