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/runtime/registry/scoped_registry.py | .py | """A per-turn view over the process tool registry.
Two things the process-global :class:`~deeptutor.runtime.registry.tool_registry.ToolRegistry`
cannot express, both of which a user-facing external-tool store needs:
* **Tools that belong to one user.** ``register()`` is a last-writer-wins dict
keyed by tool name, s... | 176 | 7,280 |
DeepTutor | deeptutor/runtime/registry/__init__.py | .py | """Runtime registries for capabilities and tools."""
from .capability_registry import CapabilityRegistry, get_capability_registry
from .tool_registry import ToolRegistry, get_tool_registry
__all__ = [
"CapabilityRegistry",
"ToolRegistry",
"get_capability_registry",
"get_tool_registry",
]
| 12 | 307 |
DeepTutor | deeptutor/runtime/registry/deferred_tools.py | .py | """
Deferred tool loading (progressive disclosure for tool schemas).
Tools flagged ``BaseTool.deferred`` (all MCP tools, by default) are NOT part
of the initial per-turn tool list. The system prompt carries a one-line
manifest per deferred tool (:func:`render_deferred_tools_manifest`); when the
model decides it needs ... | 203 | 8,011 |
DeepTutor | deeptutor/runtime/registry/tool_registry.py | .py | """
Tool Registry
=============
Central registry that discovers and manages all tools (built-in and plugin).
Provides lookup, listing, and OpenAI schema generation.
"""
from __future__ import annotations
import logging
from typing import Any
from deeptutor.core.tool_protocol import BaseTool, ToolDefinition, ToolPro... | 154 | 5,248 |
DeepTutor | deeptutor/runtime/registry/capability_registry.py | .py | """
Capability Registry
===================
Central registry for all capabilities (built-in and plugin).
"""
from __future__ import annotations
import importlib
import logging
from typing import Any
from deeptutor.core.capability_protocol import BaseCapability
from deeptutor.i18n.metadata_i18n import capability_des... | 115 | 3,789 |
DeepTutor | deeptutor/runtime/providers/allowlist.py | .py | """An allowlist of tool names with an explicit *unrestricted* state.
The turn's provider authorisation has to combine several optional whitelists
(a partner's configured filter, the caller's grant, an implicit
resource-derived grant). Modelling "no restriction" as ``None`` inside bare
set arithmetic makes both directi... | 67 | 2,369 |
DeepTutor | deeptutor/runtime/providers/scope.py | .py | """What a turn needs to know to decide which provider tools it may use.
Deliberately a plain input record, not a protocol every provider must
implement: MCP and CLI apps differ in what their grants are keyed by (tool
names vs. app ids), in what "not ready" means, and in whether preloading is
even meaningful. Forcing o... | 47 | 2,222 |
DeepTutor | deeptutor/runtime/providers/__init__.py | .py | """External tool providers: the tools a deployment or a user plugs in.
An *external provider* is something that contributes tools DeepTutor did not
ship โ an MCP server today, an installed CLI app next. What they share is the
disclosure pipeline, which already exists and is source-agnostic: one manifest
line per tool ... | 45 | 1,860 |
DeepTutor | deeptutor/runtime/providers/view.py | .py | """Assemble one turn's external-provider tool surface.
This is the composition seam that used to live inline in the chat pipeline:
start the providers, work out what this caller may use, filter the pool,
build the progressive-disclosure loader, and render the manifest block. It
lives here so the policy is testable on ... | 242 | 9,288 |
DeepTutor | deeptutor/runtime/providers/text.py | .py | """Sanitisation for text that arrives from an external tool provider.
Tool names and descriptions from an MCP server, or catalog copy for an
installed CLI app, are **third-party strings**. They reach the model through
the ``extended_tools`` system-prompt block and through tool schemas โ the
highest-trust position in a... | 92 | 3,983 |
DeepTutor | deeptutor/runtime/providers/authorize.py | .py | """Per-kind authorisation for external-provider tools.
One function per provider kind, on purpose. The two kinds do not share an
authorisation rule:
* **MCP** is granted per *tool name* (``grant.mcp_tools``) for deployment
servers, and by *ownership* for servers a user configured themselves;
* **CLI apps** will be ... | 67 | 2,822 |
DeepTutor | deeptutor/multi_user/tool_access.py | .py | """Per-user tool and exec access resolution (grant v2).
Optional built-in tools keep the partner config semantics for real users:
``None`` means "unrestricted / follow defaults", a set is an explicit
whitelist. MCP tools are different because they can proxy host-side
capabilities through configured MCP servers. For no... | 114 | 4,076 |
DeepTutor | deeptutor/multi_user/grants.py | .py | """Logical resource grants for non-admin users."""
from __future__ import annotations
from copy import deepcopy
import json
from pathlib import Path
from typing import Any
from .identity import get_user_by_id
from .paths import SYSTEM_ROOT, ensure_system_dirs
GRANTS_DIR = SYSTEM_ROOT / "grants"
def empty_grant(us... | 138 | 5,506 |
DeepTutor | deeptutor/multi_user/audit.py | .py | """Audit log for resource access and admin actions in the multi-user layer."""
from __future__ import annotations
from datetime import datetime, timezone
import json
from typing import Any
from .context import get_current_user
from .paths import SYSTEM_ROOT, ensure_system_dirs
def _audit_file():
# Resolved per... | 81 | 2,422 |
DeepTutor | deeptutor/multi_user/model_access.py | .py | """Server-side model grant resolution and redacted model views.
Grants carry LLM assignments only (grant v2): embedding and search always
resolve from the deployment's active profiles, so per-user grants for them
were never enforced and are not stored.
Two sources reach an ordinary user, and :func:`redacted_model_acc... | 168 | 7,025 |
DeepTutor | deeptutor/multi_user/personal_models.py | .py | """Owner-bound LLM profiles an ordinary user signed in for themselves.
An owner-bound profile โ an OpenAI Codex OAuth login, today โ authenticates
one *person's* subscription rather than a billable team key, so it is never
lent to another account through grants (see
:func:`~deeptutor.multi_user.model_access.is_owner_b... | 158 | 6,415 |
DeepTutor | deeptutor/multi_user/models.py | .py | """Small data models for DeepTutor's optional multi-user layer."""
from __future__ import annotations
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Literal
Role = Literal["admin", "user"]
ScopeKind = Literal["admin", "user"]
@dataclass(frozen=True, slots=True)
class User... | 84 | 1,998 |
DeepTutor | deeptutor/multi_user/partner_access.py | .py | """Partner visibility guards for non-admin users.
Partners are admin-managed, process-wide resources: the whole
``/api/v1/partners`` CRUD router is admin-gated, and a partner runs in its own
isolated workspace scope (``data/partners/{id}/``), never the caller's. A
non-admin can't create or manage partners, but an admi... | 84 | 3,074 |
DeepTutor | deeptutor/multi_user/__init__.py | .py | """Optional multi-user support for DeepTutor.
The package is deliberately isolated from the legacy single-user services.
Existing code enters it through thin adapters only when auth.json enables auth.
Backend support matrix
----------------------
The default JSON/SQLite backend (``integrations.pocketbase_url`` blank... | 24 | 1,040 |
DeepTutor | deeptutor/multi_user/router.py | .py | """Admin APIs for the optional multi-user layer."""
from __future__ import annotations
import asyncio
from typing import Any
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from deeptutor.api.routers.auth import require_admin
from deeptutor.knowledge.manager import KnowledgeBase... | 229 | 8,272 |
DeepTutor | deeptutor/multi_user/context.py | .py | """Request-local current user context."""
from __future__ import annotations
from contextvars import ContextVar, Token
from typing import Any
from .models import CurrentUser
from .paths import local_admin_user, scope_for_user
_current_user: ContextVar[CurrentUser | None] = ContextVar("deeptutor_current_user", defau... | 46 | 1,377 |
DeepTutor | deeptutor/multi_user/identity.py | .py | """Canonical identity store for the optional multi-user layer."""
from __future__ import annotations
from datetime import datetime, timezone
import json
import logging
from pathlib import Path
import secrets
import threading
from typing import Any
from uuid import uuid4
from .models import Role
from .paths import PR... | 326 | 10,963 |
DeepTutor | deeptutor/multi_user/skill_access.py | .py | """Skill visibility guards for non-admin users."""
from __future__ import annotations
from typing import Any
from fastapi import HTTPException
from .context import get_current_user
from .grants import load_grant
from .paths import get_admin_path_service
def assigned_skill_ids(user_id: str | None = None) -> set[st... | 76 | 2,554 |
DeepTutor | deeptutor/multi_user/paths.py | .py | """Path resolution for admin-local and per-user workspaces.
Everything lives under ``<runtime-home>/data`` so a deployment has exactly
one tree to mount and back up:
* ``data/user`` โ the admin workspace (admin scope root is ``data/``)
* ``data/users/<uid>`` โ one workspace per non-admin user
* ``data/pa... | 262 | 10,232 |
DeepTutor | deeptutor/multi_user/knowledge_access.py | .py | """Knowledge-base visibility and write guards for the multi-user layer."""
from __future__ import annotations
from functools import lru_cache
from pathlib import Path
from typing import Any
from fastapi import HTTPException
from deeptutor.knowledge.manager import KnowledgeBaseManager
from deeptutor.knowledge.manife... | 282 | 9,389 |
DeepTutor | deeptutor/agents/__init__.py | .py | """
Agents Module - Unified agent system for OpenTutor.
This module provides a unified BaseAgent class and module-specific agents:
- research: Deep research agents (DecomposeAgent, ResearchAgent, etc.)
- question: Question generation agents (ReAct architecture, separate base)
- chat: ``AgenticChatPipeline`` โ single-l... | 37 | 1,294 |
DeepTutor | deeptutor/agents/base_agent.py | .py | #!/usr/bin/env python
"""
Unified BaseAgent - Base class for all module agents.
This is the single source of truth for agent base functionality across:
- solve module
- research module
- co_writer module
- question module (unified in Jan 2026 refactor)
"""
from abc import ABC, abstractmethod
import inspect
import log... | 770 | 26,790 |
DeepTutor | deeptutor/agents/visualize/pipeline.py | .py | """Orchestrates the three-stage visualization generation flow."""
from __future__ import annotations
from typing import Any, Callable
from deeptutor.core.context import Attachment
from .agents import AnalysisAgent, CodeGeneratorAgent, ReviewAgent
from .models import ReviewResult, VisualizationAnalysis
class Visua... | 92 | 2,566 |
DeepTutor | deeptutor/agents/visualize/utils.py | .py | """Utility helpers for the visualize pipeline."""
from __future__ import annotations
import json
import re
import defusedxml.ElementTree as ET
from deeptutor.agents._shared.json_output import extract_json_object
_MERMAID_KEYWORDS = (
"graph",
"flowchart",
"sequenceDiagram",
"classDiagram",
"sta... | 192 | 6,645 |
DeepTutor | deeptutor/agents/visualize/models.py | .py | """Data models for the visualize pipeline."""
from __future__ import annotations
import logging
from typing import Any, Literal, get_args
from pydantic import BaseModel, Field, model_validator
logger = logging.getLogger(__name__)
RenderType = Literal[
"svg",
"chartjs",
"mermaid",
"html",
"manim... | 120 | 4,112 |
DeepTutor | deeptutor/agents/visualize/__init__.py | .py | """Visualize agents and pipeline."""
from .pipeline import VisualizePipeline
__all__ = ["VisualizePipeline"]
| 6 | 111 |
DeepTutor | deeptutor/agents/visualize/capability.py | .py | """
Visualize Capability
====================
Unified visualization capability. AnalysisAgent picks one of six render
types โ svg / chartjs / mermaid / html (text-emitting, three-stage pipeline)
or manim_video / manim_image (Manim subprocess pipeline). The result
envelope carries ``render_type`` as the discriminator s... | 575 | 23,289 |
DeepTutor | deeptutor/agents/visualize/agents/__init__.py | .py | """Agent building blocks for the visualize capability."""
from .analysis_agent import AnalysisAgent
from .code_generator_agent import CodeGeneratorAgent
from .review_agent import ReviewAgent
__all__ = [
"AnalysisAgent",
"CodeGeneratorAgent",
"ReviewAgent",
]
| 12 | 273 |
DeepTutor | deeptutor/agents/visualize/agents/review_agent.py | .py | """Repair stage: targeted fix after deterministic local validation fails."""
from __future__ import annotations
import json
from deeptutor.agents.base_agent import BaseAgent
from deeptutor.core.trace import build_trace_metadata, new_call_id
from ..models import ReviewResult, VisualizationAnalysis
from ..utils impor... | 76 | 2,540 |
DeepTutor | deeptutor/agents/visualize/agents/analysis_agent.py | .py | """Analysis stage: decide SVG vs Chart.js and produce a structured brief."""
from __future__ import annotations
from deeptutor.agents.base_agent import BaseAgent
from deeptutor.core.context import Attachment
from deeptutor.core.trace import build_trace_metadata, new_call_id
from ..models import VisualizationAnalysis... | 103 | 4,090 |
DeepTutor | deeptutor/agents/visualize/agents/code_generator_agent.py | .py | """Code generation stage: produce SVG or Chart.js code from the analysis."""
from __future__ import annotations
import json
from deeptutor.agents.base_agent import BaseAgent
from deeptutor.core.trace import build_trace_metadata, new_call_id
from ..models import VisualizationAnalysis
from ..utils import extract_code... | 118 | 4,748 |
DeepTutor | deeptutor/agents/vision_solver/__init__.py | .py | """Vision Solver Agent Module.
Single-call image analysis: read a math-problem figure and emit GeoGebra
commands to reconstruct it (with one gated repair pass). Exposed to chat and
solve through the ``geogebra_analysis`` built-in tool.
"""
from deeptutor.agents.vision_solver.vision_solver_agent import VisionSolverAge... | 11 | 356 |
DeepTutor | deeptutor/agents/vision_solver/vision_solver_agent.py | .py | """Vision Solver Agent โ single-call image โ GeoGebra command generation.
Collapses the old four-stage pipeline (BBox โ Analysis โ GGBScript โ
Reflection) into ONE vision call that reads the figure and emits GeoGebra
commands directly, plus a single gated repair pass that only fires when the
first call produced no usa... | 190 | 7,206 |
DeepTutor | deeptutor/agents/math_animator/pipeline.py | .py | """Orchestrates the math animator generation flow."""
from __future__ import annotations
import time
from typing import Any, Callable
from deeptutor.core.context import Attachment
from .agents import (
CodeGeneratorAgent,
ConceptAnalysisAgent,
ConceptDesignAgent,
SummaryAgent,
VisualReviewAgent,... | 281 | 9,168 |
DeepTutor | deeptutor/agents/math_animator/request_config.py | .py | """Validated request config for the math animator capability."""
from __future__ import annotations
from typing import Any, Literal
from pydantic import BaseModel, ConfigDict, Field, ValidationError
class MathAnimatorRequestConfig(BaseModel):
model_config = ConfigDict(extra="forbid")
output_mode: Literal[... | 39 | 1,195 |
DeepTutor | deeptutor/agents/math_animator/renderer.py | .py | """Manim rendering service for the math animator capability."""
from __future__ import annotations
import asyncio
from pathlib import Path
import re
import subprocess
import sys
import threading
from typing import Awaitable, Callable
from deeptutor.services.path_service import get_path_service
from .models import R... | 251 | 9,395 |
DeepTutor | deeptutor/agents/math_animator/utils.py | .py | """Utility helpers for the math animator pipeline."""
from __future__ import annotations
import re
from deeptutor.agents._shared.json_output import extract_json_object
def slugify_filename(value: str, fallback: str) -> str:
cleaned = re.sub(r"[^a-zA-Z0-9._-]+", "-", (value or "").strip()).strip("-")
return... | 54 | 1,638 |
DeepTutor | deeptutor/agents/math_animator/duration_utils.py | .py | """Duration helpers for math animator prompts."""
from __future__ import annotations
import re
_SECOND_PATTERN = re.compile(
r"(?P<value>\d+(?:\.\d+)?)\s*(?:s|sec|secs|second|seconds|็ง(?:้)?)",
re.IGNORECASE,
)
_MINUTE_PATTERN = re.compile(
r"(?P<value>\d+(?:\.\d+)?)\s*(?:min(?:ute)?s?|ๅ้|m(?![sS]))",
... | 37 | 1,011 |
DeepTutor | deeptutor/agents/math_animator/models.py | .py | """Shared data models for the math animator pipeline."""
from __future__ import annotations
from pydantic import BaseModel, ConfigDict, Field
class ConceptAnalysis(BaseModel):
model_config = ConfigDict(extra="ignore")
learning_goal: str = ""
math_focus: list[str] = Field(default_factory=list)
visua... | 96 | 2,322 |
DeepTutor | deeptutor/agents/math_animator/__init__.py | .py | """Math animator agents and pipeline."""
from .pipeline import MathAnimatorPipeline
from .request_config import (
MathAnimatorRequestConfig,
validate_math_animator_request_config,
)
__all__ = [
"MathAnimatorPipeline",
"MathAnimatorRequestConfig",
"validate_math_animator_request_config",
]
| 14 | 312 |
DeepTutor | deeptutor/agents/math_animator/visual_review.py | .py | """Frame extraction utilities for visual quality review."""
from __future__ import annotations
import asyncio
import base64
from pathlib import Path
from typing import Awaitable, Callable
from deeptutor.core.context import Attachment
from deeptutor.services.path_service import get_path_service
from .models import R... | 150 | 5,396 |
DeepTutor | deeptutor/agents/math_animator/retry_manager.py | .py | """Retry loop for render-fix-regenerate workflow."""
from __future__ import annotations
import asyncio
from typing import Awaitable, Callable
from .models import GeneratedCode, RetryAttempt, VisualReviewResult
from .renderer import ManimRenderError, ManimRenderService
def _is_non_retriable_environment_error(messag... | 161 | 7,520 |
DeepTutor | deeptutor/agents/math_animator/capability.py | .py | """Math animator capability."""
from __future__ import annotations
import importlib.util
import time
from typing import Any
from deeptutor.agents._shared.capability_result import emit_capability_result
from deeptutor.core.agentic.usage import UsageTracker
from deeptutor.core.capability_protocol import BaseCapability... | 309 | 12,657 |
DeepTutor | deeptutor/agents/math_animator/agents/concept_design_agent.py | .py | """Concept design stage for math animator."""
from __future__ import annotations
import json
from deeptutor.agents.base_agent import BaseAgent
from deeptutor.core.trace import build_trace_metadata, new_call_id
from ..models import ConceptAnalysis, SceneDesign
from ..utils import extract_json_object
class ConceptD... | 68 | 2,195 |
DeepTutor | deeptutor/agents/math_animator/agents/concept_analysis_agent.py | .py | """Concept analysis stage for math animator."""
from __future__ import annotations
from deeptutor.agents.base_agent import BaseAgent
from deeptutor.core.context import Attachment
from deeptutor.core.trace import build_trace_metadata, new_call_id
from deeptutor.services.prompt import get_prompt_manager
from ..models ... | 89 | 3,304 |
DeepTutor | deeptutor/agents/math_animator/agents/summary_agent.py | .py | """Summary stage for math animator."""
from __future__ import annotations
import json
from deeptutor.agents.base_agent import BaseAgent
from deeptutor.core.trace import build_trace_metadata, new_call_id
from ..models import ConceptAnalysis, RenderResult, SceneDesign, SummaryPayload
from ..utils import extract_json_... | 70 | 2,357 |
DeepTutor | deeptutor/agents/math_animator/agents/__init__.py | .py | """Agent building blocks for the math animator capability."""
from .code_generator_agent import CodeGeneratorAgent
from .concept_analysis_agent import ConceptAnalysisAgent
from .concept_design_agent import ConceptDesignAgent
from .summary_agent import SummaryAgent
from .visual_review_agent import VisualReviewAgent
__... | 16 | 457 |
DeepTutor | deeptutor/agents/math_animator/agents/code_generator_agent.py | .py | """Code generation and repair stages for math animator."""
from __future__ import annotations
import json
from deeptutor.agents.base_agent import BaseAgent
from deeptutor.core.trace import build_trace_metadata, new_call_id
from ..models import ConceptAnalysis, GeneratedCode, SceneDesign
from ..utils import build_re... | 139 | 5,058 |
DeepTutor | deeptutor/agents/math_animator/agents/visual_review_agent.py | .py | """Visual quality review stage for math animator outputs."""
from __future__ import annotations
import json
from deeptutor.agents.base_agent import BaseAgent
from deeptutor.core.context import Attachment
from deeptutor.core.trace import build_trace_metadata, new_call_id
from deeptutor.services.llm import supports_vi... | 101 | 3,389 |
DeepTutor | deeptutor/agents/chat/agent_loop.py | .py | """Single-loop chat agent.
One chat turn = ONE agent loop over a single growing conversation:
* each round is one LLM call; its text streams to the user as a ``content``
block, and its tool calls are dispatched with their ``role=tool`` results
appended back into the conversation;
* a round that DOES call tools is... | 868 | 36,974 |
DeepTutor | deeptutor/agents/chat/prompt_blocks.py | .py | """Structured prompt assembly for the chat agent loop."""
from __future__ import annotations
from typing import Any
from deeptutor.capabilities.protocol import PromptBlock
from deeptutor.core.context import UnifiedContext
from deeptutor.services.prompt.language import append_language_directive
class ChatPromptAsse... | 190 | 7,701 |
DeepTutor | deeptutor/agents/chat/__init__.py | .py | """
Chat Module - conversational AI with session management.
This module provides:
- ChatAgent: Legacy conversational agent with RAG/Web Search support
- AgenticChatPipeline: exploring agent loop + respond stage with autonomous tool use
- SessionManager: Chat session persistence and management
Usage:
from deeptut... | 27 | 800 |
DeepTutor | deeptutor/agents/chat/dsml_tool_calls.py | .py | """Fallback parser for DeepSeek's text-format ("DSML") tool calls.
Some DeepSeek deployments (notably local/source setups whose OpenAI-compatible
endpoint doesn't advertise native function calling) emit tool calls as markup in
the assistant *content* channel instead of as structured ``delta.tool_calls``.
The markup mi... | 292 | 10,930 |
DeepTutor | deeptutor/agents/chat/capability.py | .py | """Agentic chat capability."""
from __future__ import annotations
from deeptutor.agents.chat.agentic_pipeline import CHAT_OPTIONAL_TOOLS, AgenticChatPipeline
from deeptutor.core.capability_protocol import BaseCapability, CapabilityManifest
from deeptutor.core.context import UnifiedContext
from deeptutor.core.stream_b... | 28 | 1,049 |
DeepTutor | deeptutor/agents/chat/session_manager.py | .py | #!/usr/bin/env python
"""
SessionManager - Chat session persistence and management.
This module handles:
- Creating new chat sessions
- Updating sessions with new messages
- Retrieving session history
- Listing recent sessions
- Deleting sessions
Now inherits from BaseSessionManager for consistent behavior across all... | 180 | 5,212 |
DeepTutor | deeptutor/agents/chat/chat_agent.py | .py | #!/usr/bin/env python
"""
ChatAgent - Lightweight conversational AI with multi-turn support.
This agent provides:
- Multi-turn conversation with history management
- Token-based context truncation
- Optional RAG and Web Search augmentation
- Streaming response generation
Uses the unified LLM factory from BaseAgent fo... | 435 | 13,794 |
DeepTutor | deeptutor/agents/chat/agentic_pipeline.py | .py | """Chat capability assembly for the exploring-loop agent."""
from __future__ import annotations
import asyncio
import logging
from typing import Any
from deeptutor.agents._shared.tool_composition import (
ToolMountFlags,
compose_enabled_tools,
default_optional_tools,
user_has_memory,
user_has_not... | 1,564 | 66,575 |
DeepTutor | deeptutor/agents/chat/context_budget.py | .py | """Per-turn accounting of what the chat loop put in the model's context window.
The composer surfaces "how full is the window, and what is filling it". Those
numbers only mean something if they describe the request the provider actually
received, so everything here measures *already-assembled* material โ the
:class:`P... | 322 | 11,335 |
DeepTutor | deeptutor/agents/research/pipeline.py | .py | """ResearchPipeline โ agentic-engine-based replacement for the legacy
multi-agent ``ResearchPipeline``.
Phase shape:
* **Phase 1 (Rephrase)** โ a mini agentic loop over ``THINK`` / ``TOOL``
/ ``FINISH`` whose only available tool is ``ask_user``. Up to 3
ask_user rounds (each with 1-4 questions on one card). FINIS... | 2,872 | 110,257 |
DeepTutor | deeptutor/agents/research/request_config.py | .py | """Validated request config and intent-to-policy mapping for deep research.
Tool composition lives in :mod:`deeptutor.agents._shared.tool_composition`
โ the same shim chat uses. Research has no separate ``sources`` knob:
whatever tools the user enables in the composer become available to the
per-block research loop, w... | 250 | 8,078 |
DeepTutor | deeptutor/agents/research/capability.py | .py | """Deep Research capability โ agentic-engine-based deep research.
Thin shim that delegates to :class:`ResearchPipeline`. All orchestration
โ rephrase (mini agentic loop with ``ask_user``), decompose, per-block
research loops with ``THINK`` / ``TOOL`` / ``APPEND`` / ``FINISH``,
queue scheduler, and iterative reporting ... | 100 | 4,349 |
DeepTutor | deeptutor/agents/research/data_structures.py | .py | #!/usr/bin/env python
"""
DR-in-KG 2.0 Core Data Structures
Includes: TopicBlock, ToolTrace, DynamicTopicQueue
"""
from dataclasses import asdict, dataclass, field
from datetime import datetime
import difflib
from enum import Enum
import json
from pathlib import Path
import re
from typing import Any
from deeptutor.ut... | 571 | 19,289 |
DeepTutor | deeptutor/agents/research/mode_strategy.py | .py | """Mode strategy abstraction for deep research.
Each research mode (notes, report, comparison, learning_path) is represented
as a ``ModeStrategy`` dataclass. ``STRATEGIES`` acts as the single source of
truth that ``request_config._build_mode_policy`` delegates to.
``validate_output`` provides lightweight post-genera... | 150 | 5,020 |
DeepTutor | deeptutor/agents/research/utils/token_tracker.py | .py | #!/usr/bin/env python
"""
Token Tracker - LLM Token usage and cost tracking system (DR-in-KG version)
References student_TA/solve_agents/utils/token_tracker.py, with minor trimming and added global singleton getter method.
"""
from dataclasses import asdict, dataclass, field
from datetime import datetime
import json
f... | 282 | 10,284 |
DeepTutor | deeptutor/agents/research/utils/json_utils.py | .py | #!/usr/bin/env python
"""
JSON Utils - JSON parsing and validation utilities
- Robustly extract JSON from LLM text output
- Provide strict structure validation and error messages
"""
import json
import re
from typing import Any, Dict, Iterable, List, Union
def extract_json_from_text(text: str) -> Union[Dict[str, Any... | 95 | 2,447 |
DeepTutor | deeptutor/agents/research/utils/__init__.py | .py | """Research utility exports."""
from .json_utils import (
ensure_json_dict,
ensure_json_list,
ensure_keys,
extract_json_from_text,
json_to_text,
safe_json_loads,
)
from .token_tracker import TokenTracker, get_token_tracker
__all__ = [
"extract_json_from_text",
"ensure_json_dict",
"... | 23 | 448 |
DeepTutor | deeptutor/agents/research/utils/citation_manager.py | .py | #!/usr/bin/env python
"""
CitationManager - Citation management system
Responsible for extracting citation information from tool calls and managing citation JSON files
"""
import asyncio
from datetime import datetime
import html
import json
from pathlib import Path
from typing import Any
from deeptutor.services.path_... | 906 | 34,310 |
DeepTutor | deeptutor/agents/notebook/summarize_agent.py | .py | """Notebook summarization agent."""
from __future__ import annotations
from typing import AsyncGenerator
from deeptutor.services.llm import clean_thinking_tags, get_llm_config, get_token_limit_kwargs
from deeptutor.services.llm import stream as llm_stream
from deeptutor.services.prompt.manager import get_prompt_mana... | 127 | 4,338 |
DeepTutor | deeptutor/agents/notebook/__init__.py | .py | """Notebook agents."""
from .analysis_agent import NotebookAnalysisAgent
from .summarize_agent import NotebookSummarizeAgent
__all__ = ["NotebookAnalysisAgent", "NotebookSummarizeAgent"]
| 7 | 189 |
DeepTutor | deeptutor/agents/notebook/analysis_agent.py | .py | """Notebook analysis agent for cross-record grounding."""
from __future__ import annotations
import logging
from typing import Any, Awaitable, Callable
from deeptutor.core.stream import StreamEvent, StreamEventType
from deeptutor.core.trace import build_trace_metadata, derive_trace_metadata, new_call_id
from deeptut... | 387 | 14,104 |
DeepTutor | deeptutor/agents/question/pipeline.py | .py | """QuestionPipeline โ agentic-engine-based replacement for ``AgentCoordinator``.
Phase shape:
* **Phase 1 (Explore)** โ one agentic loop over ``THINK`` / ``TOOL`` /
``FINISH``, using the same tool composition as chat. The ``FINISH``
text streams live into the chat bubble as a brief, user-facing preface
(e.g., "... | 2,162 | 86,057 |
DeepTutor | deeptutor/agents/question/request_config.py | .py | """Runtime config builder for ``QuestionPipeline``.
Mirrors the shape used by :mod:`deeptutor.agents.research.request_config`,
but with a much smaller surface โ the question pipeline only needs a
handful of knobs out of the service config:
* ``exploring.max_iterations`` (int, default 8) โ agentic-loop cap for the
E... | 78 | 2,618 |
DeepTutor | deeptutor/agents/question/mimic_source.py | .py | """Exam-paper โ QuizTemplate adapter for mimic mode.
Wraps the (sync, IO-heavy) MinerU parsing backend (local CLI or cloud API,
selected via ``document_parsing.json``) + the LLM question extractor so the capability
layer can hand mimic templates to :class:`QuestionPipeline` via its
``templates_override`` entry. Each e... | 161 | 6,061 |
DeepTutor | deeptutor/agents/question/__init__.py | .py | """Question generation package.
The main entry point is :class:`~deeptutor.agents.question.pipeline.QuestionPipeline`.
Lightweight names (``FollowupAgent``, ``QuizTemplate``, ``QuizPair``, etc.)
are resolved lazily so callers that only need one symbol don't eagerly
import the full pipeline + its LLM dependencies.
"""
... | 34 | 1,150 |
DeepTutor | deeptutor/agents/question/coordinator.py | .py | """Compatibility adapter for legacy question-generation entry points.
The old ``AgentCoordinator`` implementation was replaced by
``QuestionPipeline``. A few API/tool modules still import the coordinator
name, so this module preserves that surface while delegating all real work
to the new pipeline.
"""
from __future_... | 243 | 9,042 |
DeepTutor | deeptutor/agents/question/capability.py | .py | """Deep Question Capability.
Routes one user turn through the right quiz-generation path:
* followup โ single-call ``FollowupAgent`` reply about one prior question.
* custom mode โ new ``QuestionPipeline`` (explore โ plan โ per-question loop).
* mimic mode โ same pipeline, but PDF parsing produces the templates
an... | 448 | 19,056 |
DeepTutor | deeptutor/agents/question/history.py | .py | """Quiz history loader โ surfaces prior quiz items in the same session.
Used by :class:`QuestionPipeline` so the Explore phase can articulate
which topics have already been tested, which the learner got wrong, and
how the next round should avoid duplication / optionally target weak
spots.
Single public entry point:
... | 104 | 3,959 |
DeepTutor | deeptutor/agents/question/agents/followup_agent.py | .py | #!/usr/bin/env python
"""
Single-call follow-up agent for quiz question threads.
"""
from __future__ import annotations
from typing import Any
from deeptutor.agents.base_agent import BaseAgent
from deeptutor.core.trace import build_trace_metadata, new_call_id
from deeptutor.services.prompt.language import append_lan... | 119 | 4,534 |
DeepTutor | deeptutor/agents/question/agents/__init__.py | .py | """Question generation sub-agents.
Currently only the standalone single-call ``FollowupAgent`` lives here โ
the per-question / per-batch agents (idea_agent, generator) were
replaced by the single :mod:`deeptutor.agents.question.pipeline` module
during the Phase A โ C refactor.
"""
from importlib import import_module
... | 20 | 639 |
DeepTutor | deeptutor/agents/_shared/tool_composition.py | .py | """Per-turn tool composition policy shared by chat / quiz pipelines.
Owns the rule "given the user's composer toggles + the turn's context
flags, what tools should be enabled?". Lives outside any single pipeline
so chat and quiz can't disagree about which tools the user controls vs.
which the pipeline auto-mounts.
Tw... | 260 | 10,347 |
DeepTutor | deeptutor/agents/_shared/__init__.py | .py | """Helpers shared by capability pipelines (chat, solve, quiz, ...).
Cross-pipeline policy that doesn't belong on the generic ``core.agentic``
engine (which stays capability-agnostic) and doesn't belong on a single
pipeline either. Each module here documents the contract its consumers
must hold to.
"""
| 8 | 304 |
DeepTutor | deeptutor/agents/_shared/json_output.py | .py | """Parsing helpers shared by agents that consume structured model output."""
from __future__ import annotations
import json
import re
from typing import Any
def extract_json_object(text: str) -> dict[str, Any]:
"""Extract the first usable JSON object from raw model output."""
raw = (text or "").strip()
... | 63 | 1,711 |
DeepTutor | deeptutor/agents/_shared/capability_result.py | .py | """Shared plumbing for capability ``run()`` endpoints.
Capabilities all converge on the same final emission:
await stream.result({"response": ..., ...}, source="<cap>")
The basic chat capability also attaches a per-turn ``cost_summary`` so the
frontend can render ``$cost ยท tokens ยท calls`` in its message footer.... | 50 | 1,623 |
DeepTutor | deeptutor/app/__init__.py | .py | """Public application facades for CLI, Web, and SDK adapters."""
from .facade import CapabilityAvailability, DeepTutorApp, TurnRequest
__all__ = ["CapabilityAvailability", "DeepTutorApp", "TurnRequest"]
| 6 | 205 |
DeepTutor | deeptutor/app/facade.py | .py | """Stable application-layer facade for DeepTutor entry points."""
from __future__ import annotations
from dataclasses import dataclass, field
import importlib.util
import json
from typing import Any, AsyncIterator
from deeptutor.runtime.registry.capability_registry import get_capability_registry
from deeptutor.servi... | 215 | 8,131 |
DeepTutor | deeptutor/co_writer/storage.py | .py | """
Co-Writer Document Storage
==========================
Per-document directory + manifest persistence with atomic writes.
Layout (relative to ``data/user/workspace/co-writer/``)::
documents/
โโโ doc_{doc_id}/
โ โโโ manifest.json # { id, title, content, created_at, updated_at }
โโโ doc_{doc_id2}... | 251 | 8,046 |
DeepTutor | deeptutor/co_writer/edit_agent.py | .py | """
EditAgent - Co-writer editing agent.
Inherits from unified BaseAgent.
"""
import asyncio
from datetime import datetime
import json
from typing import Any, Literal
import uuid
from deeptutor.agents.base_agent import BaseAgent
from deeptutor.co_writer.storage import _atomic_write_json
from deeptutor.runtime.registr... | 374 | 13,318 |
DeepTutor | deeptutor/partners/network.py | .py | """Network security utilities for partner channels โ SSRF protection.
Stricter than ``deeptutor.services.mcp.network`` (which deliberately allows
RFC1918 because MCP servers are often LAN-hosted): channel media URLs come
from external IM platforms, so every private/internal range is blocked.
Ported from nanobot's ``s... | 102 | 3,558 |
DeepTutor | deeptutor/partners/__init__.py | .py | """Partners โ IM-connected companions driven by the DeepTutor chat agent loop.
This package hosts the channel (IM) layer: the chat-platform integrations,
the message bus that decouples them from the agent runtime, and their
configuration schema. The agent runtime itself lives in
``deeptutor.services.partners`` and reu... | 12 | 478 |
DeepTutor | deeptutor/partners/transcription.py | .py | """Voice transcription provider using Groq."""
import os
from pathlib import Path
import httpx
from loguru import logger
class GroqTranscriptionProvider:
"""
Voice transcription provider using Groq's Whisper API.
Groq offers extremely fast transcription with a generous free tier.
"""
def __ini... | 62 | 1,820 |
DeepTutor | deeptutor/partners/helpers.py | .py | """Utility functions shared by the partner channel layer."""
from datetime import datetime
from pathlib import Path
import re
def detect_image_mime(data: bytes) -> str | None:
"""Detect image MIME type from magic bytes, ignoring file extension."""
if data[:8] == b"\x89PNG\r\n\x1a\n":
return "image/pn... | 118 | 3,793 |
DeepTutor | deeptutor/partners/config/__init__.py | .py | """Configuration module for Partners channels."""
from deeptutor.partners.config.paths import (
get_data_dir,
get_media_dir,
get_partner_dir,
get_partner_media_dir,
get_partner_sessions_dir,
get_partner_workspace,
get_runtime_subdir,
)
from deeptutor.partners.config.schema import Base, Chan... | 25 | 560 |
DeepTutor | deeptutor/partners/config/schema.py | .py | """Configuration schema โ Pydantic models for partner channels."""
from __future__ import annotations
from pydantic import BaseModel, ConfigDict, Field
from pydantic.alias_generators import to_camel
class Base(BaseModel):
"""Base model that accepts both camelCase and snake_case keys."""
model_config = Conf... | 51 | 1,450 |
DeepTutor | deeptutor/partners/config/paths.py | .py | """Path helpers for the Partners data tree (``data/partners/``)."""
from __future__ import annotations
from pathlib import Path
from deeptutor.partners.helpers import ensure_dir
def _base_dir() -> Path:
# Anchored to the admin workspace root (data/partners), NOT the
# current-user path service: partner run... | 54 | 1,846 |
DeepTutor | deeptutor/partners/bus/__init__.py | .py | """Message bus module for decoupled channel-agent communication."""
from deeptutor.partners.bus.events import InboundMessage, OutboundMessage
from deeptutor.partners.bus.queue import MessageBus
__all__ = ["MessageBus", "InboundMessage", "OutboundMessage"]
| 7 | 258 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.