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/i18n/status_i18n.py | .py | """Shared i18n helper for capability status / UI strings.
Capability ``run()`` methods stream short status messages to the chat UI
(``stream.thinking``, ``stream.progress``, ``stream.error``). Those strings
must respect the user's locale. This helper wires them into the existing
``PromptManager`` so each capability ke... | 61 | 2,366 |
DeepTutor | deeptutor/i18n/__init__.py | .py | """Localization helpers.
Two complementary pieces live here:
* :mod:`~deeptutor.i18n.metadata_i18n` — static localized display copy for
built-in capabilities and tools (used by the settings UI / API).
* :mod:`~deeptutor.i18n.status_i18n` — per-feature localized status-string
lookup wired into the :class:`PromptMa... | 25 | 718 |
DeepTutor | deeptutor/events/__init__.py | .py | """Application event bus utilities."""
from .event_bus import (
Event,
EventBus,
EventType,
get_event_bus,
)
__all__ = [
"Event",
"EventBus",
"EventType",
"get_event_bus",
]
| 16 | 208 |
DeepTutor | deeptutor/events/event_bus.py | .py | """
Event Bus
=========
Asynchronous event bus for inter-module communication.
Supports publish/subscribe pattern with non-blocking event delivery.
"""
from __future__ import annotations
import asyncio
from dataclasses import dataclass, field
from datetime import datetime
from enum import Enum
import logging
from ty... | 206 | 6,625 |
DeepTutor | deeptutor/tools/ask_user.py | .py | """Build the payload for the ``ask_user`` tool.
The tool packages one-to-four structured questions into a payload that
the chat pipeline interprets as a "pause this same turn until the user
answers" signal (``ToolResult.pause_for_user``). The frontend reads the
same payload off ``tool_result.metadata.ask_user`` and re... | 274 | 9,649 |
DeepTutor | deeptutor/tools/write_note.py | .py | """Create or edit a single notebook record from the chat agent.
Replaces the older ``save_to_notebook`` tool. Two modes:
* **append**: create a NEW record in the target notebook. The body is
either an auto-rendered transcript (when ``content`` is empty — the
default; mirrors a human clicking 'Save to notebook' on... | 466 | 15,504 |
DeepTutor | deeptutor/tools/tex_chunker.py | .py | """
TeX Chunker - LaTeX text chunking tool
Features:
1. Intelligent chunking of LaTeX content (by section or token count)
2. Token estimation (based on GPT tokenizer)
3. Maintain context coherence (overlap between chunks)
Author: DeepTutor Team
Version: v1.0
Based on: TODO.md specification
"""
import re
import tikt... | 342 | 11,556 |
DeepTutor | deeptutor/tools/paper_search_tool.py | .py | """
ArXiv search tool for preprint discovery.
This utility searches arXiv and returns lightweight metadata suitable for
tool usage in chat / playground flows.
"""
import asyncio
from datetime import datetime
import logging
import re
import arxiv
logger = logging.getLogger(__name__)
_FETCH_MULTIPLIER = 2
_MAX_FETCH... | 208 | 6,034 |
DeepTutor | deeptutor/tools/web_fetch.py | .py | """HTTP fetch + readable-content extraction for the chat ``web_fetch`` tool.
Kept deliberately self-contained: a single async entrypoint
:py:func:`fetch_url_as_markdown` that takes a URL and returns either the
extracted text (with a ``url`` field for citation) or a structured error.
The chat pipeline calls it via the ... | 263 | 9,609 |
DeepTutor | deeptutor/tools/brainstorm.py | .py | """
Brainstorm tool - stateless breadth-first idea exploration.
This tool performs a single LLM call to explore multiple plausible directions
for a topic and briefly justify each one.
"""
from __future__ import annotations
import logging
from typing import Any
logger = logging.getLogger(__name__)
_SYSTEM_PROMPT = ... | 105 | 3,058 |
DeepTutor | deeptutor/tools/partner_memory.py | .py | """Partner-only memory + history tools.
A partner has a *split* memory model that the product chat does not:
* its OWN long-term memory lives in the partner's synthetic workspace
(``data/partners/<id>/workspace/memory``) and is the only thing
``partner_memorize`` ever writes to — a partner can never mutate the
... | 307 | 12,304 |
DeepTutor | deeptutor/tools/__init__.py | .py | """Public entry points for the tool layer."""
from __future__ import annotations
import importlib
_LAZY_EXPORTS = {
"brainstorm": (".brainstorm", "brainstorm"),
"rag_search": (".rag_tool", "rag_search"),
"reason": (".reason", "reason"),
"web_search": (".web_search", "web_search"),
"PaperSearchToo... | 43 | 1,575 |
DeepTutor | deeptutor/tools/media_gen_tool.py | .py | """Image- and video-generation chat tools.
Thin BaseTool front-ends over the ``imagegen`` / ``videogen`` services. Each
call generates media via the active catalog model, writes the bytes into the
turn's public workspace, and returns the files as artifacts — reusing the exact
same ``collect_public_artifacts`` conventi... | 262 | 9,961 |
DeepTutor | deeptutor/tools/github_query.py | .py | """Read-only GitHub queries via the ``gh`` CLI.
Pure-function shape on top of an injectable ``run_command`` callback so
tests don't need to mock ``asyncio.subprocess``. The tool exposes a
restricted set of operations:
* ``pr`` — view a pull request (title, state, checks, reviews)
* ``issue`` — view an issue (title... | 230 | 7,209 |
DeepTutor | deeptutor/tools/web_search.py | .py | """
Web Search Tool - Simple entry point for agents
This module provides a simple interface to the web search service.
All search logic is implemented in deeptutor/services/search/.
Usage:
from deeptutor.tools.web_search import web_search
# Simple usage
result = web_search("What is AI?")
# With prov... | 66 | 1,547 |
DeepTutor | deeptutor/tools/solve_tool.py | .py | """Compatibility exports for solve loop-plugin tools.
The solve loop capability owns the implementation under
``deeptutor.capabilities.solve.tools``. This module keeps a stable import path
for the built-in tool registry and any external users.
"""
from deeptutor.capabilities.solve.tools import (
SOLVE_TOOL_NAMES,... | 23 | 544 |
DeepTutor | deeptutor/tools/exec_tool.py | .py | """
Sandboxed shell execution tool for chat.
This is the chat-side counterpart to TutorBot's ExecTool, but every command
runs through the :mod:`deeptutor.services.sandbox` layer rather than a raw
subprocess. The pipeline mounts the turn's workspace read-write and exposes
it as the working directory; the deny-pattern g... | 157 | 5,734 |
DeepTutor | deeptutor/tools/tex_downloader.py | .py | """
TeX Downloader - LaTeX source code download tool
Features:
1. Download LaTeX source from ArXiv
2. Extract and locate main tex file
3. Read tex content
Author: DeepTutor Team
Version: v1.0
Based on: TODO.md specification
"""
import logging
import os
from pathlib import Path
import re
import shutil
import tarfile
... | 257 | 8,043 |
DeepTutor | deeptutor/tools/rag_tool.py | .py | """RAG query tool — thin wrapper around :class:`RAGService`.
The chat pipeline always passes an explicit ``kb_name`` selected by the user;
this module therefore never resolves aliases or falls back to a default KB.
"""
from __future__ import annotations
import asyncio
from typing import Dict, List, Optional
from de... | 111 | 3,329 |
DeepTutor | deeptutor/tools/list_notebook.py | .py | """List the user's notebooks or the records inside a single notebook.
Two modes, picked by whether ``notebook_id`` is supplied:
* **Index mode** (``notebook_id`` empty): list every notebook the
active user owns — id, name, description, record count, last-updated.
Equivalent to the sidebar view a human sees.
* **D... | 212 | 7,168 |
DeepTutor | deeptutor/tools/cron_tool.py | .py | """Implementation behind the built-in ``cron`` tool."""
from __future__ import annotations
from dataclasses import dataclass, field
from datetime import datetime
from typing import Any
from deeptutor.services.cron import (
CronJob,
CronOwner,
CronSchedule,
get_cron_service,
)
@dataclass
class CronA... | 143 | 5,199 |
DeepTutor | deeptutor/tools/reason.py | .py | """
Reason tool — stateless LLM deep-reasoning call.
When the solver agent needs deeper analysis, logical deduction, or synthesis
of already-gathered information but no external tool (RAG / web / code) is
required, it delegates to this tool. A single, stateless LLM call produces
a step-by-step reasoning trace that is... | 120 | 4,132 |
DeepTutor | deeptutor/tools/file_tools.py | .py | """Workspace file tools for chat skill/script workflows."""
from __future__ import annotations
import difflib
from pathlib import Path
from typing import Any
from deeptutor.core.tool_protocol import BaseTool, ToolDefinition, ToolParameter, ToolResult
from deeptutor.tools.prompting import load_prompt_hints
def _res... | 291 | 11,674 |
DeepTutor | deeptutor/tools/mastery_tool.py | .py | """Compatibility exports for mastery path tools.
The mastery loop capability owns the implementation under
``deeptutor.capabilities.mastery.tools``. This module keeps the historical
import path stable for the built-in tool registry, capability manifests, and
external users.
"""
from deeptutor.capabilities.mastery.too... | 28 | 681 |
DeepTutor | deeptutor/tools/vision/block_parser.py | .py | """Parser for GGBScript code blocks in LLM output."""
from dataclasses import dataclass, field
from enum import Enum
import re
from deeptutor.tools.vision.ggb_validator import validate_ggbscript
class BlockType(str, Enum):
"""Types of special blocks in the response."""
GGBSCRIPT = "ggbscript"
GEOGEBRA ... | 252 | 8,849 |
DeepTutor | deeptutor/tools/vision/coord_transform.py | .py | """Coordinate transformation utilities.
Converts between BBox pixel coordinates and GeoGebra math coordinates.
BBox coordinate system:
- Origin at top-left
- X-axis: right is positive
- Y-axis: down is positive
GeoGebra coordinate system:
- Origin at center (or user-specified)
- X-axis: right is positive
- Y-axis: u... | 437 | 12,073 |
DeepTutor | deeptutor/tools/vision/ggb_validator.py | .py | """GeoGebra command validator and fixer.
This module validates GeoGebra commands and attempts to fix common mistakes
that LLMs might make when generating GeoGebra scripts.
"""
from dataclasses import dataclass, field
import re
@dataclass
class ValidationResult:
"""Result of validating a GeoGebra command."""
... | 284 | 7,741 |
DeepTutor | deeptutor/tools/vision/__init__.py | .py | """Vision tools for image processing and GeoGebra support."""
from deeptutor.tools.vision.block_parser import (
BlockType,
GGBBlock,
ParsedContent,
StreamingBlockParser,
parse_ggb_blocks,
)
from deeptutor.tools.vision.coord_transform import (
DEFAULT_GGB_COORD,
GGBCoordSystem,
ImageDime... | 80 | 1,792 |
DeepTutor | deeptutor/tools/vision/image_utils.py | .py | """Image processing utilities - URL download and format conversion."""
import base64
import logging
from urllib.parse import urlparse
import httpx
logger = logging.getLogger(__name__)
# Supported image MIME types
SUPPORTED_IMAGE_TYPES = {
"image/jpeg": "jpeg",
"image/jpg": "jpg",
"image/png": "png",
... | 211 | 5,597 |
DeepTutor | deeptutor/tools/builtin/__init__.py | .py | """Built-in tool implementations and metadata."""
from __future__ import annotations
import asyncio
import json
import logging
from typing import Any
from deeptutor.capabilities.mastery import MASTERY_TOOL_TYPES
from deeptutor.capabilities.obsidian import OBSIDIAN_TOOL_TYPES
from deeptutor.capabilities.solve import ... | 1,707 | 68,688 |
DeepTutor | deeptutor/tools/prompting/__init__.py | .py | """Prompt hint loading and rendering helpers for tools."""
from __future__ import annotations
from collections import OrderedDict
from pathlib import Path
from typing import Any
import yaml
from deeptutor.core.tool_protocol import ToolAlias, ToolPromptHints
ToolHintEntry = tuple[str, ToolPromptHints]
_GUIDELINE_H... | 231 | 8,951 |
DeepTutor | deeptutor/tools/question/exam_mimic.py | .py | #!/usr/bin/env python
"""
Thin mimic entrypoint.
The orchestration now lives in deeptutor/agents/question/coordinator.py.
"""
from __future__ import annotations
from typing import Any, Callable
from deeptutor.agents.question import AgentCoordinator
from deeptutor.services.llm.config import get_llm_config
WsCallbac... | 71 | 2,241 |
DeepTutor | deeptutor/tools/question/__init__.py | .py | """
Question Tools - Question generation system toolset
Tools for PDF parsing, question extraction, and mimic entrypoint.
"""
# MinerU parsing now lives in the shared parse layer
# (deeptutor/services/parsing/engines/mineru); re-exported here for the question
# toolset's backward-compatible public API.
from deeptutor... | 39 | 1,133 |
DeepTutor | deeptutor/tools/question/question_extractor.py | .py | #!/usr/bin/env python
"""
Extract question information from MinerU-parsed exam papers
This script reads MinerU-parsed markdown files and content_list.json,
uses LLM to analyze and extract all questions, including question content and related images.
Uses the unified LLM Factory for all LLM calls, supporting:
- Cloud ... | 414 | 14,099 |
DeepTutor | deeptutor/services/path_service.py | .py | #!/usr/bin/env python
"""
PathService - centralized runtime storage layout for ``data/user``.
Runtime data is constrained to:
data/user/
├── chat_history.db
├── logs/
├── settings/
└── workspace/
├── memory/
├── notebook/
├── co-writer/
├── book/
└── chat/
├── chat/
├── deep_solve/... | 463 | 16,058 |
DeepTutor | deeptutor/services/codebuddy_auth.py | .py | """Process-local coordinator for CodeBuddy SDK authentication."""
from __future__ import annotations
import asyncio
from typing import Any
class CodeBuddyAuthService:
"""Probe existing SDK auth and keep one browser login flow alive."""
def __init__(self) -> None:
self._lock = asyncio.Lock()
... | 240 | 8,559 |
DeepTutor | deeptutor/services/codebuddy_credentials.py | .py | """Read the CodeBuddy desktop/CLI login state without the Agent SDK.
CodeBuddy's IDE plugin and CLI share a single OAuth session file whose name
matches ``authentication.id`` in the CLI's ``product.json``
(``Tencent-Cloud.coding-copilot``). Reading it lets DeepTutor call the
CodeBuddy cloud over plain HTTP the same wa... | 364 | 12,402 |
DeepTutor | deeptutor/services/file_io.py | .py | """Small, dependency-free helpers for durable service files."""
from __future__ import annotations
import json
import os
from pathlib import Path
import tempfile
from typing import Any
def atomic_write_json(path: Path, payload: dict[str, Any]) -> None:
"""Write *payload* as UTF-8 JSON without exposing a partial... | 64 | 1,874 |
DeepTutor | deeptutor/services/__init__.py | .py | """
Services Layer
==============
Unified service layer for DeepTutor providing:
- LLM client and configuration
- Embedding client and configuration
- RAG pipelines and components
- Prompt management
- Web Search providers
- System setup utilities
- Configuration loading
Usage:
from deeptutor.services.llm import ... | 87 | 2,572 |
DeepTutor | deeptutor/services/auth.py | .py | """
Authentication service for DeepTutor.
Disabled by default (auth.enabled=false) so localhost users are unaffected.
When enabled, guards all API routes with JWT bearer tokens.
Quick setup (single user via data/user/settings/auth.json):
1. Set enabled=true
2. Set username=<your username>
3. Generate a pa... | 379 | 13,046 |
DeepTutor | deeptutor/services/generation_http.py | .py | """Shared HTTP plumbing for media-generation providers (imagegen / videogen).
Image- and video-generation endpoints across OpenAI, Volcengine Ark (Seedream /
Seedance) and compatible gateways share the same auth + base-URL conventions as
the rest of the OpenAI-compatible cluster. This module factors out the few
helper... | 75 | 2,698 |
DeepTutor | deeptutor/services/provider_registry.py | .py | """Provider registry for DeepTutor LLM routing.
Single source of truth for provider metadata. Adding a new provider:
1. Add a ProviderSpec to PROVIDERS below.
Done. Env vars, config matching, status display all derive from here.
Order matters — it controls match priority and fallback. Gateways first.
"""
from __... | 578 | 18,867 |
DeepTutor | deeptutor/services/pocketbase_client.py | .py | """
PocketBase client singleton.
Only initialised when integrations.pocketbase_url is configured.
All other code checks ``is_pocketbase_enabled()`` before calling
``get_pb_client()`` to avoid import-time failures when PocketBase is
not configured.
Token validation uses PocketBase's auth-refresh endpoint rather than
l... | 197 | 6,570 |
DeepTutor | deeptutor/services/skill/hub.py | .py | """
Skill hub providers
===================
Import skills from external registries ("hubs") into the local skill layer.
A hub skill is the same artefact DeepTutor already speaks natively — a
directory with a ``SKILL.md`` (YAML frontmatter + markdown playbook) plus
optional support files — so importing is a fetch + ad... | 1,006 | 38,478 |
DeepTutor | deeptutor/services/skill/__init__.py | .py | """Skill service: capability-skill packages loaded on demand via read_skill."""
from deeptutor.services.skill.service import (
SkillService,
SkillSummaryEntry,
get_skill_service,
render_skills_manifest,
)
__all__ = [
"SkillService",
"SkillSummaryEntry",
"get_skill_service",
"render_ski... | 16 | 337 |
DeepTutor | deeptutor/services/skill/service.py | .py | """
SkillService
============
Capability-skill storage and runtime loading, nanobot-style.
A skill is a self-contained capability package the model consults *on
demand*: a ``SKILL.md`` playbook plus optional ``references/`` (and, once the
execution sandbox ships, ``scripts/``). Skills are never injected wholesale
int... | 1,052 | 39,538 |
DeepTutor | deeptutor/services/skill/credentials.py | .py | """
Local store for skill-hub publish credentials
==============================================
Per-hub bearer tokens minted by ``skill login`` (browser OAuth) and consumed by
``skill publish`` / ``skill update``. Kept in the settings dir as
``skill_hub_auth.json`` with ``0600`` perms — separate from ``skill_hubs.jso... | 103 | 3,190 |
DeepTutor | deeptutor/services/skill/taxonomy.py | .py | """
Skill classification taxonomy
=============================
The single Python source of truth for EduHub's skill classification — the
required ``track`` (one-of) plus the optional faceting dimensions
(``language``, ``domains``, ``stages``, ``forms``, ``audiences``). It mirrors
the eduhub web's ``src/data/taxonomy.... | 315 | 10,792 |
DeepTutor | deeptutor/services/settings/interface_settings.py | .py | """
Interface (UI) settings reader.
This is the canonical backend source for user-selected UI language/theme stored in:
data/user/settings/interface.json
"""
from __future__ import annotations
from collections.abc import Mapping
import json
from typing import Any
from deeptutor.services.path_service import get_pa... | 113 | 3,689 |
DeepTutor | deeptutor/services/sandbox/backends.py | .py | """
Sandbox backends: one class per isolation mechanism.
* :class:`RunnerSidecarBackend` — submits the command to a separate runner
container over HTTP (SYSTEM isolation). The deployment answer for Docker:
the main app stays least-privileged and never executes untrusted shell.
* :class:`BwrapBackend` — wraps the c... | 230 | 8,588 |
DeepTutor | deeptutor/services/sandbox/__init__.py | .py | """Sandboxed shell execution: pluggable isolation backends + per-user quota."""
from deeptutor.services.sandbox.service import (
SandboxService,
exec_capability_available,
get_sandbox_service,
reset_sandbox_service,
)
from deeptutor.services.sandbox.spec import (
ExecRequest,
ExecResult,
Is... | 28 | 587 |
DeepTutor | deeptutor/services/sandbox/spec.py | .py | """
Sandbox value types: isolation levels, exec requests, and exec results.
Kept dependency-free so both the backends and the skill/exec layers can
import them without pulling in the backend implementations.
"""
from __future__ import annotations
from collections.abc import Sequence
from dataclasses import dataclass... | 142 | 4,902 |
DeepTutor | deeptutor/services/sandbox/quota.py | .py | """
Per-user execution quotas.
Two cheap in-process guards against a runaway or abusive session:
* a concurrency cap (semaphore per user) — no more than N executions in
flight at once;
* a sliding 60-second rate cap — no more than M executions started per
minute.
In-process is sufficient for the single-container... | 79 | 2,680 |
DeepTutor | deeptutor/services/sandbox/artifacts.py | .py | """Artifact discovery for sandboxed exec workspaces."""
from __future__ import annotations
from dataclasses import dataclass
import mimetypes
from pathlib import Path
from urllib.parse import quote
from deeptutor.services.path_service import PathService, get_path_service
@dataclass(frozen=True, slots=True)
class S... | 119 | 3,782 |
DeepTutor | deeptutor/services/sandbox/service.py | .py | """
Sandbox service facade.
The single entry point the rest of the app uses. It owns the chosen backend,
caches its liveness probe, enforces per-user quotas, and answers the
capability questions the skill/exec layers ask:
* :func:`exec_capability_available` — does a usable sandbox of this kind
exist at all? (drives... | 133 | 4,941 |
DeepTutor | deeptutor/services/sandbox/config.py | .py | """
Sandbox configuration and backend selection.
The active backend is chosen from environment so it tracks the deployment
shape without per-user config:
* ``DEEPTUTOR_SANDBOX_RUNNER_URL`` set ⇒ runner sidecar (Docker deployment);
* else on Linux with a functional ``bwrap`` ⇒ bwrap (bare-metal);
* else, only when ``D... | 93 | 3,012 |
DeepTutor | deeptutor/services/sandbox/runner/server.py | .py | """Sandbox runner sidecar HTTP server (standard-library only).
This process runs *inside* the dedicated ``sandbox-runner`` container and is the
only place where untrusted shell commands are actually executed. The main app
never runs them itself; it submits work here over HTTP
(:class:`deeptutor.services.sandbox.backen... | 373 | 15,055 |
DeepTutor | deeptutor/services/sandbox/runner/__init__.py | .py | """Sandbox runner sidecar: a tiny HTTP service that executes untrusted shell.
Runs in its own least-privileged container, isolated from the main app. The
main app talks to it via :class:`deeptutor.services.sandbox.backends.RunnerSidecarBackend`,
pointed at it through ``DEEPTUTOR_SANDBOX_RUNNER_URL``.
"""
| 7 | 307 |
DeepTutor | deeptutor/services/storage/__init__.py | .py | """Pluggable storage backends for chat-session artifacts.
Currently exposes only :mod:`attachment_store`, which persists user-uploaded
chat attachments to disk so the frontend can preview them after the original
base64 payload is dropped from the message record.
"""
from deeptutor.services.storage.attachment_store im... | 19 | 504 |
DeepTutor | deeptutor/services/storage/attachment_store.py | .py | """Persistent storage for chat attachments.
The chat turn runtime writes the bytes of every uploaded attachment here
*before* the document extractor runs. Once persisted, the URL is recorded on
the message and the in-memory base64 is dropped (extractor still clears it
for office docs to save DB space). The frontend la... | 257 | 9,431 |
DeepTutor | deeptutor/services/imagegen/__init__.py | .py | """Image-generation service — text-to-image via the active model catalog.
Public facade used by the chat tool, the API router and the config test runner.
Config is resolved from ``services.imagegen`` exactly like llm/embedding/tts, so
image providers are configured through the same Settings catalog UI.
"""
from __fut... | 48 | 1,655 |
DeepTutor | deeptutor/services/imagegen/config.py | .py | """Resolved runtime configuration for image-generation providers.
This dataclass is the read-side adapter between the model catalog
(``services.imagegen``) and the HTTP adapter. It mirrors the shape of
:class:`TTSConfig` so a single OpenAI-compatible adapter can cover OpenAI
DALL·E / gpt-image, Volcengine Ark Seedream... | 40 | 1,371 |
DeepTutor | deeptutor/services/imagegen/base.py | .py | """Base abstraction for image-generation adapters."""
from __future__ import annotations
from abc import ABC, abstractmethod
from deeptutor.services.imagegen.config import ImagegenConfig
class BaseImagegenAdapter(ABC):
"""Abstract text-to-image adapter."""
@abstractmethod
async def generate(
s... | 25 | 627 |
DeepTutor | deeptutor/services/imagegen/adapters/__init__.py | .py | """Image-generation adapter registry.
Adapters are stateless singletons keyed by the ``adapter`` field on the resolved
config. The OpenAI-compatible adapter covers OpenAI, Volcengine Ark Seedream and
compatible gateways; register bespoke providers by adding new keys here.
"""
from __future__ import annotations
from ... | 31 | 1,268 |
DeepTutor | deeptutor/services/imagegen/adapters/chat_completions.py | .py | """Chat-completions image-generation adapter (OpenRouter-style).
Some gateways generate images through the chat endpoint rather than the OpenAI
Images API: ``POST {base}/chat/completions`` with ``modalities: ["image",
"text"]`` returns the image inside the assistant message::
{"choices": [{"message": {"images": [... | 115 | 4,745 |
DeepTutor | deeptutor/services/imagegen/adapters/openai_compat.py | .py | """OpenAI-compatible image-generation adapter.
Covers OpenAI DALL·E / gpt-image, Volcengine Ark Seedream and any gateway that
exposes ``POST {base}/images/generations``. Handles both response shapes —
``data[].b64_json`` (preferred: bytes inline) and ``data[].url`` (downloaded) —
so the caller always receives raw byte... | 97 | 3,765 |
DeepTutor | deeptutor/services/llm/types.py | .py | """Shared LLM response data models."""
from collections.abc import AsyncGenerator
import logging
from pydantic import BaseModel, Field
logger = logging.getLogger(__name__)
class TutorResponse(BaseModel):
"""LLM completion response container."""
content: str
raw_response: dict[str, object] = Field(defa... | 53 | 1,190 |
DeepTutor | deeptutor/services/llm/context_window.py | .py | """Helpers for reasoning about model context-window budgets."""
from __future__ import annotations
from typing import Any
DEFAULT_CONTEXT_WINDOW_FALLBACK = 16_384
MAX_EFFECTIVE_CONTEXT_WINDOW = 1_000_000
LARGE_CONTEXT_MODEL_DEFAULT = 65_536
KNOWN_LARGE_CONTEXT_MARKERS = (
"gpt-4.1",
"gpt-4o",
"gpt-5",
... | 79 | 2,153 |
DeepTutor | deeptutor/services/llm/multimodal.py | .py | """
Multimodal Message Utilities
=============================
Converts plain-text messages + image attachments into the multimodal
message format expected by vision-capable LLMs.
Supports:
- OpenAI-compatible API (content array with image_url blocks)
- Anthropic API (content array with image source blocks)
"""
from... | 368 | 13,418 |
DeepTutor | deeptutor/services/llm/telemetry.py | .py | """
LLM Telemetry
=============
Basic telemetry tracking for LLM calls.
"""
from collections.abc import Awaitable, Callable
import functools
import logging
from typing import TypeVar
logger = logging.getLogger(__name__)
T = TypeVar("T")
def track_llm_call(
provider_name: str,
) -> Callable[[Callable[..., Awa... | 47 | 1,140 |
DeepTutor | deeptutor/services/llm/utils.py | .py | """
LLM Utilities
=============
Shared helpers for URL handling, response parsing, and content cleanup.
"""
from __future__ import annotations
from collections.abc import Mapping, Sequence
import ipaddress
import os
import re
from urllib.parse import urlparse
CLOUD_DOMAINS = [
".openai.com",
".anthropic.com... | 330 | 8,800 |
DeepTutor | deeptutor/services/llm/executors.py | .py | """Provider-backed LLM executors (openai + anthropic SDKs, no litellm)."""
from __future__ import annotations
from collections.abc import AsyncGenerator
import logging
import os
from typing import Any
import uuid
from openai import AsyncOpenAI, BadRequestError
from deeptutor.services.llm.capabilities import disable... | 279 | 9,034 |
DeepTutor | deeptutor/services/llm/exceptions.py | .py | """
LLM Service Exceptions
======================
Custom exception classes for the LLM service.
Provides a consistent exception hierarchy for better error handling.
Maintains parity with upstream dev branch.
"""
class LLMError(Exception):
"""Base exception for all LLM-related errors."""
def __init__(
... | 161 | 4,054 |
DeepTutor | deeptutor/services/llm/cloud_provider.py | .py | """
Cloud LLM Provider
==================
Handles all cloud API LLM calls (OpenAI, DeepSeek, Anthropic, etc.)
Provides both complete() and stream() methods.
"""
from collections.abc import AsyncGenerator, Mapping
import logging
import threading
from typing import cast
import aiohttp
from deeptutor.services.config i... | 924 | 34,451 |
DeepTutor | deeptutor/services/llm/provider_factory.py | .py | """Factory for services-layer provider runtime objects."""
from __future__ import annotations
import asyncio
from collections import OrderedDict
import contextlib
import hashlib
import json
import threading
from typing import Any
from deeptutor.services.llm.config import LLMConfig, get_llm_config
from deeptutor.serv... | 187 | 6,565 |
DeepTutor | deeptutor/services/llm/__init__.py | .py | """
LLM Service
===========
Unified LLM service for all DeepTutor modules.
Architecture:
Agents (ChatAgent, SolveAgent, etc.)
↓
BaseAgent.call_llm() / stream_llm()
↓
LLM Factory (complete / stream)
↓
┌─────────┴─────────┐
↓ ↓
Cl... | 174 | 4,525 |
DeepTutor | deeptutor/services/llm/traffic_control.py | .py | """Traffic control primitives for LLM providers."""
from __future__ import annotations
import asyncio
import logging
import time
from types import TracebackType
logger = logging.getLogger(__name__)
class TrafficController:
"""
Controls concurrency and rate limits for LLM providers.
Protects both the l... | 126 | 4,325 |
DeepTutor | deeptutor/services/llm/error_mapping.py | .py | """
Error Mapping - Map provider-specific errors to unified exceptions.
"""
from __future__ import annotations
from collections.abc import Callable
from dataclasses import dataclass
import logging
# Import unified exceptions from exceptions.py
from .exceptions import (
LLMAPIError,
LLMAuthenticationError,
... | 88 | 2,634 |
DeepTutor | deeptutor/services/llm/registry.py | .py | """
LLM Provider Registry
====================
Simple provider registration system for LLM providers.
"""
from collections.abc import Callable
# Global registry for LLM providers
_provider_registry: dict[str, type] = {}
def register_provider(name: str) -> Callable[[type], type]:
"""
Decorator to register a... | 72 | 1,430 |
DeepTutor | deeptutor/services/llm/openai_http_client.py | .py | """HTTP client helpers for OpenAI-compatible SDK providers."""
from __future__ import annotations
import logging
import os
import threading
from typing import Any
import httpx
from deeptutor.services.config import load_system_settings
from deeptutor.services.llm.exceptions import LLMConfigError
logger = logging.ge... | 56 | 1,748 |
DeepTutor | deeptutor/services/llm/client.py | .py | """
LLM Client
==========
Unified LLM client for all DeepTutor services.
Note: This is a legacy interface. Prefer using the factory functions directly:
from deeptutor.services.llm import complete, stream
"""
from collections.abc import Awaitable, Callable
import logging
from typing import Any, cast
from .capabi... | 253 | 8,715 |
DeepTutor | deeptutor/services/llm/capabilities.py | .py | """
Provider Capabilities
=====================
Centralized configuration for LLM provider capabilities.
This replaces scattered hardcoded checks throughout the codebase.
Usage:
from deeptutor.services.llm.capabilities import get_capability, supports_response_format
# Check if a provider supports response_fo... | 608 | 22,378 |
DeepTutor | deeptutor/services/llm/provider_registry.py | .py | """Compatibility re-export for the shared provider registry."""
from deeptutor.services.provider_registry import * # noqa: F403
| 4 | 130 |
DeepTutor | deeptutor/services/llm/factory.py | .py | """Unified services-layer LLM factory."""
from __future__ import annotations
import asyncio
from collections.abc import AsyncGenerator, Mapping
import contextlib
from types import SimpleNamespace
from typing import Any, TypedDict
from deeptutor.config.settings import settings
from deeptutor.services.provider_registr... | 670 | 21,955 |
DeepTutor | deeptutor/services/llm/reasoning_params.py | .py | """Reasoning/thinking parameters for OpenAI-compatible provider calls."""
from __future__ import annotations
from typing import Any
_THINKING_STYLE_MAP = {
"thinking_type": lambda enabled: {"thinking": {"type": "enabled" if enabled else "disabled"}},
"enable_thinking": lambda enabled: {"enable_thinking": ena... | 157 | 6,333 |
DeepTutor | deeptutor/services/llm/local_provider.py | .py | """
Local LLM Provider
==================
Handles all local/self-hosted LLM calls (LM Studio, Ollama, vLLM, llama.cpp, etc.)
Uses aiohttp instead of httpx for better compatibility with local servers.
Key features:
- Uses aiohttp (httpx has known 502 issues with some local servers like LM Studio)
- Handles thinking ta... | 391 | 13,322 |
DeepTutor | deeptutor/services/llm/config.py | .py | """
LLM Configuration
=================
Configuration management for LLM services.
Loads from data/user/settings/model_catalog.json.
"""
from __future__ import annotations
from contextvars import ContextVar, Token
from dataclasses import dataclass, replace
import logging
import os
from pathlib import Path
import re
... | 294 | 8,389 |
DeepTutor | deeptutor/services/llm/request_compat.py | .py | """Provider-error classifiers used by retry and graceful-degradation paths."""
from __future__ import annotations
def error_text(exc: Exception) -> str:
"""Return the best available lowercase provider error body."""
response = getattr(exc, "response", None)
body = (
getattr(exc, "body", None)
... | 79 | 2,121 |
DeepTutor | deeptutor/services/llm/provider_core/anthropic_provider.py | .py | """Anthropic provider — direct SDK integration for Claude models.
Handles message format conversion (OpenAI -> Anthropic Messages API),
prompt caching, extended thinking, tool calls, and streaming.
"""
from __future__ import annotations
import asyncio
from collections.abc import Awaitable, Callable
import re
import ... | 570 | 21,663 |
DeepTutor | deeptutor/services/llm/provider_core/azure_openai_provider.py | .py | """Azure OpenAI provider backed by the OpenAI SDK Responses API."""
from __future__ import annotations
import asyncio
from collections.abc import Awaitable, Callable
from typing import Any
import uuid
from openai import AsyncOpenAI
from deeptutor.services.llm.openai_http_client import openai_client_kwargs
from deep... | 195 | 6,698 |
DeepTutor | deeptutor/services/llm/provider_core/__init__.py | .py | """Services-layer provider runtime with lazy SDK-backed implementations."""
from __future__ import annotations
from importlib import import_module
from typing import TYPE_CHECKING
from .base import GenerationSettings, LLMProvider, LLMResponse, ToolCallRequest
if TYPE_CHECKING:
from .anthropic_provider import An... | 53 | 1,872 |
DeepTutor | deeptutor/services/llm/provider_core/openai_compat_provider.py | .py | """OpenAI-compatible provider for all non-Anthropic LLM APIs.
Uses the official ``openai.AsyncOpenAI`` SDK to talk to any OpenAI-compatible
endpoint (OpenAI, DeepSeek, Gemini, Moonshot, MiniMax, gateways, local, etc.).
"""
from __future__ import annotations
import asyncio
from collections.abc import Awaitable, Calla... | 874 | 33,307 |
DeepTutor | deeptutor/services/llm/provider_core/github_copilot_provider.py | .py | """GitHub Copilot provider with graceful fallback to existing local auth."""
from __future__ import annotations
from collections.abc import Awaitable, Callable
import time
from typing import Any
import httpx
from openai import AuthenticationError
from deeptutor.services.llm.provider_core.base import LLMResponse
fro... | 223 | 7,968 |
DeepTutor | deeptutor/services/llm/provider_core/openai_codex_provider.py | .py | """OpenAI Codex Responses provider backed by DeepTutor's private OAuth service."""
from __future__ import annotations
from collections.abc import Awaitable, Callable
import hashlib
import json
from typing import Any
import httpx
from loguru import logger
from deeptutor.services.codex_auth import CodexAuthError, get... | 240 | 9,415 |
DeepTutor | deeptutor/services/llm/provider_core/codebuddy_models.py | .py | """Model catalog lookup for CodeBuddy.
The cloud has no public model-list route, so the catalog comes from the config
the CodeBuddy CLI caches on disk. The CLI subprocess probe is only used as a
fallback, and ``default`` resolves on every deployment.
"""
from __future__ import annotations
import importlib.util
from... | 37 | 1,133 |
DeepTutor | deeptutor/services/llm/provider_core/codebuddy_http_provider.py | .py | """CodeBuddy provider that talks to the cloud over plain HTTP.
The CodeBuddy cloud exposes an OpenAI-compatible ``/chat/completions`` under
``<endpoint>/v2`` and accepts the OAuth session that the IDE plugin and CLI
already store on disk. That makes the Agent SDK (a bundled headless CLI
binary) unnecessary for chat, s... | 244 | 8,220 |
DeepTutor | deeptutor/services/llm/provider_core/codebuddy_provider.py | .py | """CodeBuddy Agent SDK provider."""
from __future__ import annotations
import asyncio
from collections import OrderedDict
from collections.abc import Awaitable, Callable
from contextlib import asynccontextmanager
from copy import deepcopy
from dataclasses import dataclass, field
import json
import os
import re
import... | 840 | 29,488 |
DeepTutor | deeptutor/services/llm/provider_core/base.py | .py | """Base LLM provider interface."""
from __future__ import annotations
from abc import ABC, abstractmethod
import asyncio
from collections.abc import Awaitable, Callable, Sequence
from dataclasses import dataclass, field
import inspect
import json
from typing import Any
from loguru import logger
@dataclass
class To... | 459 | 16,271 |
DeepTutor | deeptutor/services/llm/provider_core/openai_responses/__init__.py | .py | """Shared helpers for Responses API providers."""
from .converters import (
adapt_chat_kwargs_to_responses,
convert_messages,
convert_tools,
convert_user_message,
split_tool_call_id,
)
from .parsing import (
FINISH_REASON_MAP,
consume_sdk_stream,
consume_sse,
iter_sse,
map_finis... | 32 | 651 |
DeepTutor | deeptutor/services/llm/provider_core/openai_responses/parsing.py | .py | """Parse Responses API SSE streams and SDK response objects."""
from __future__ import annotations
from collections.abc import Awaitable, Callable
from dataclasses import dataclass
import json
from typing import Any, AsyncGenerator
import httpx
import json_repair
from loguru import logger
from deeptutor.services.ll... | 382 | 14,780 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.