chore: import upstream snapshot with attribution
Tests / Import Check (Python 3.13) (push) Has been cancelled
Tests / Import Check (Python 3.14) (push) Has been cancelled
Tests / Python Tests (Python 3.11) (push) Has been cancelled
Tests / Python Tests (Python 3.12) (push) Has been cancelled
Tests / Python Tests (Python 3.14) (push) Has been cancelled
Tests / Test Summary (push) Has been cancelled
Tests / Lint and Format (push) Has been cancelled
Tests / Web Node Tests (push) Has been cancelled
Tests / Import Check (Python 3.11) (push) Has been cancelled
Tests / Import Check (Python 3.12) (push) Has been cancelled
Tests / Python Tests (Python 3.13) (push) Has been cancelled

This commit is contained in:
wehub-resource-sync
2026-07-13 13:00:43 +08:00
commit e4dcfc49aa
1668 changed files with 324490 additions and 0 deletions
+138
View File
@@ -0,0 +1,138 @@
# ============================================
# DeepTutor Docker Ignore File
# ============================================
# Excludes files and directories from the Docker build context
# to improve build speed and reduce image size
# ============================================
# ============================================
# Git
# ============================================
.git
.gitignore
.gitattributes
# ============================================
# Documentation
# ============================================
*.md
!README.md
docs/
assets/gifs/
assets/figs/
assets/README/
# ============================================
# Python
# ============================================
__pycache__/
**/__pycache__/
*.py[cod]
*$py.class
*.so
*.egg
*.egg-info/
.eggs/
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
MANIFEST
# Virtual environments
.env
*.env
env/
venv/
ENV/
.venv/
env.bak/
venv.bak/
DeepTutor.env
# Pytest cache
.pytest_cache/
.coverage
htmlcov/
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# ============================================
# Node.js
# ============================================
node_modules/
**/node_modules/
web/node_modules/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Next.js
.next/
web/.next/
out/
web/out/
# ============================================
# IDE and Editor
# ============================================
.idea/
.vscode/
*.swp
*.swo
*~
.DS_Store
# ============================================
# Docker
# ============================================
Dockerfile*
docker-compose*.yml
.docker/
.dockerignore
# ============================================
# User Data (will be mounted as volumes)
# ============================================
data/user/
data/knowledge_bases/
run_code_workspace/
# ============================================
# Development and Testing
# ============================================
develop/
scripts/extract_numbered_items.sh
*.log
logs/
*.bak
*.tmp
# ============================================
# Temporary and Cache Files
# ============================================
.cache/
cache/
**/cache/
tmp/
temp/
*.tmp
*.temp
# ============================================
# License and Communication
# ============================================
LICENSE
Communication.md
+25
View File
@@ -0,0 +1,25 @@
# ============================================
# DeepTutor (podman compose) — host-side configuration
# ============================================
# Copy to .env and edit. `.env` is gitignored.
#
# All values are loopback bindings on the HOST side. The container-side
# ports come from data/user/settings/system.json (backend_port, frontend_port).
# Edit those + `podman compose restart deeptutor` to change the in-container
# ports. This file is for shifting the host-side mapping only.
#
# The API base URL the browser uses is NOT a compose env var. The
# entrypoint reads `DEEPTUTOR_API_BASE_URL` from
# data/user/settings/system.json on every start (preferring the
# in-network `next_public_api_base`, then the external override
# `next_public_api_base_external`, then `http://localhost:${BACKEND_PORT}`),
# and web/proxy.ts rewrites /api/* and /ws/* to it at request time.
# ============================================
# Host-side loopback bindings (override if 8001/3782/8090 are taken)
HOST_PORT_BACKEND=8001
HOST_PORT_FRONTEND=3782
HOST_PORT_POCKETBASE=8090
# Time zone passed into both backend and frontend.
TZ=UTC
+18
View File
@@ -0,0 +1,18 @@
*.mp4 filter=lfs diff=lfs merge=lfs -text
# Force critical build and script files to use LF line endings for cross-platform compatibility
# This prevents CRLF-related security issues in Docker containers and shell scripts
Dockerfile text eol=lf
docker-compose.yml text eol=lf
docker-compose.*.yml text eol=lf
*.sh text eol=lf
*.py text eol=lf
*.yaml text eol=lf
*.yml text eol=lf
*.md text eol=lf
*.txt text eol=lf
*.env text eol=lf
*.json text eol=lf
*.toml text eol=lf
*.cfg text eol=lf
*.ini text eol=lf
+88
View File
@@ -0,0 +1,88 @@
name: Bug Report
description: File a bug report
title: "[Bug]:"
labels: ["bug", "triage"]
body:
- type: checkboxes
id: existingcheck
attributes:
label: Do you need to file an issue?
description: Please help us manage our time by avoiding duplicates and common bugs with the steps below.
options:
- label: I have searched the existing issues and this bug is not already filed.
- label: I believe this is a legitimate bug, not just a question or feature request.
- type: textarea
id: description
attributes:
label: Describe the bug
description: A clear and concise description of what the bug is.
placeholder: What went wrong?
- type: textarea
id: reproduce
attributes:
label: Steps to reproduce
description: Steps to reproduce the behavior.
placeholder: |
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
- type: textarea
id: expected_behavior
attributes:
label: Expected Behavior
description: A clear and concise description of what you expected to happen.
placeholder: What should have happened?
- type: dropdown
id: module
attributes:
label: Related Module
description: Which module is this bug related to?
options:
- Dashboard
- Knowledge Base Management
- Smart Solver
- Question Generator
- Deep Research
- Co-Writer
- Notebook
- Guided Learning
- Idea Generation
- API/Backend
- Frontend/Web
- Other
validations:
required: true
- type: textarea
id: configused
attributes:
label: Configuration Used
description: The DeepTutor configuration used (if applicable).
placeholder: |
# Paste your config here or describe the settings
- type: textarea
id: screenshotslogs
attributes:
label: Logs and screenshots
description: If applicable, add screenshots and logs to help explain your problem.
placeholder: Add logs and screenshots here
- type: textarea
id: additional_information
attributes:
label: Additional Information
description: |
- DeepTutor Version: e.g., v0.5.0
- Operating System: e.g., macOS 14.0, Windows 11, Ubuntu 22.04
- Python Version: e.g., 3.11.0
- Node.js Version: e.g., 18.17.0
- Browser (if applicable): e.g., Chrome 120, Firefox 121
- Related Issues: e.g., #1
- Any other relevant information.
value: |
- DeepTutor Version:
- Operating System:
- Python Version:
- Node.js Version:
- Browser (if applicable):
- Related Issues:
+1
View File
@@ -0,0 +1 @@
blank_issues_enabled: false
+58
View File
@@ -0,0 +1,58 @@
name: Documentation Issue
description: Report an inaccuracy, broken link, missing topic, or unclear explanation in the docs at deeptutor.info
title: "[Docs]: "
labels: ["docs", "triage"]
body:
- type: checkboxes
id: existingcheck
attributes:
label: Before filing
options:
- label: I have searched the existing docs issues and this report is not already filed.
- label: This is about the docs at https://deeptutor.info — not a product bug.
- type: input
id: page
attributes:
label: Page URL
description: Which page does the issue affect?
placeholder: https://deeptutor.info/docs/...
validations:
required: true
- type: dropdown
id: kind
attributes:
label: What kind of issue?
options:
- Inaccurate or out-of-date content
- Broken link / 404
- Command or example that does not work
- Screenshot does not match the current product
- Missing topic / coverage gap
- Typo / formatting / wording
- Other
validations:
required: true
- type: textarea
id: problem
attributes:
label: What's wrong?
description: Quote the affected text or describe the issue.
placeholder: e.g. "Get Started → Setup Tour references `scripts/start_tour.py` which doesn't exist in the repo."
validations:
required: true
- type: textarea
id: expected
attributes:
label: What did you expect?
description: Optional — what should the docs say or show instead?
placeholder: e.g. "The PyPI install path should be the recommended entry, matching the README."
- type: textarea
id: environment
attributes:
label: Environment (optional)
description: Only if relevant to the issue (browser, OS, DeepTutor version).
placeholder: |
- Browser:
- DeepTutor version (if checked locally):
- OS:
+78
View File
@@ -0,0 +1,78 @@
name: EduHub / Skill Registry
description: Report an issue with EduHub — the DeepTutor skill registry (site, API, CLI, or a published skill)
title: "[EduHub]:"
labels: ["eduhub", "triage"]
body:
- type: markdown
attributes:
value: |
EduHub is DeepTutor's skill registry at https://eduhub.deeptutor.info.
Use this template for the EduHub web site, the ClawHub-compatible API, the `eduhub` CLI,
or a specific published skill. For bugs in the DeepTutor app itself, use the Bug Report template.
- type: checkboxes
id: existingcheck
attributes:
label: Do you need to file an issue?
description: Please help us manage our time by avoiding duplicates with the steps below.
options:
- label: I have searched the existing issues and this is not already filed.
- label: I have read the usage guide at https://eduhub.deeptutor.info/how-to-use
- type: dropdown
id: area
attributes:
label: Area
description: Which part of EduHub is this about?
options:
- Web site (eduhub.deeptutor.info)
- HTTP API (/api/v1)
- CLI (eduhub command)
- A published skill (install / content / metadata)
- Report a skill for removal (policy / copyright / security)
- Publishing a skill
- Other
validations:
required: true
- type: input
id: skill_slug
attributes:
label: Skill slug
description: If this is about a specific skill, its slug (e.g. socratic-tutor). Leave blank otherwise.
placeholder: socratic-tutor
- type: textarea
id: description
attributes:
label: Describe the issue
description: A clear and concise description of the problem.
placeholder: What happened? What did you expect to happen?
validations:
required: true
- type: textarea
id: reproduce
attributes:
label: Steps to reproduce
description: Steps to reproduce the behavior (if applicable).
placeholder: |
1. Run `eduhub install <slug>`
2. ...
3. See error
- type: textarea
id: logs
attributes:
label: Logs and screenshots
description: Paste the full command output or browser console errors.
render: shell
- type: textarea
id: environment
attributes:
label: Environment
description: |
- eduhub CLI Version: run `eduhub --version` (CLI issues only)
- Operating System: e.g., macOS 14.0, Windows 11, Ubuntu 22.04
- Node.js Version: e.g., 20.x
- Registry: e.g., https://eduhub.deeptutor.info
value: |
- eduhub CLI Version:
- Operating System:
- Node.js Version:
- Registry:
@@ -0,0 +1,52 @@
name: Feature Request
description: File a feature request
labels: ["enhancement"]
title: "[Feature Request]:"
body:
- type: checkboxes
id: existingcheck
attributes:
label: Do you need to file a feature request?
description: Please help us manage our time by avoiding duplicates and common feature request with the steps below.
options:
- label: I have searched the existing feature request and this feature request is not already filed.
- label: I believe this is a legitimate feature request, not just a question or bug.
- type: textarea
id: feature_request_description
attributes:
label: Feature Request Description
description: A clear and concise description of the feature request you would like.
placeholder: What does this feature request add or improve?
- type: dropdown
id: module
attributes:
label: Related Module
description: Which module would this feature affect?
options:
- Dashboard
- Knowledge Base Management
- Smart Solver
- Question Generator
- Deep Research
- Co-Writer
- Notebook
- Guided Learning
- Idea Generation
- API/Backend
- Frontend/Web
- Other
validations:
required: true
- type: textarea
id: use_case
attributes:
label: Use Case
description: Describe the problem this feature would solve or the use case it would enable.
placeholder: What problem does this feature solve?
- type: textarea
id: additional_context
attributes:
label: Additional Context
description: Add any other context or screenshots about the feature request here.
placeholder: Any additional information, mockups, or examples
+47
View File
@@ -0,0 +1,47 @@
name: Question
description: Ask a general question
labels: ["question"]
title: "[Question]:"
body:
- type: checkboxes
id: existingcheck
attributes:
label: Do you need to ask a question?
description: Please help us manage our time by avoiding duplicates and common questions with the steps below.
options:
- label: I have searched the existing questions and discussions and this question is not already answered.
- label: I believe this is a legitimate question, not just a bug or feature request.
- type: textarea
id: question
attributes:
label: Your Question
description: A clear and concise description of your question.
placeholder: What is your question?
- type: dropdown
id: module
attributes:
label: Related Module
description: Which module is your question related to?
options:
- Dashboard
- Knowledge Base Management
- Smart Solver
- Question Generator
- Deep Research
- Co-Writer
- Notebook
- Guided Learning
- Idea Generation
- API/Backend
- Frontend/Web
- Installation/Setup
- General
validations:
required: true
- type: textarea
id: context
attributes:
label: Additional Context
description: Provide any additional context or details that might help us understand your question better.
placeholder: Add any relevant information here (code snippets, error messages, configuration, etc.)
+12
View File
@@ -0,0 +1,12 @@
version: "1"
rules:
- base: main
upstream: HKUDS:main
mergeMethod: hardreset
mergeUnstable: true
- base: dev
upstream: HKUDS:dev
mergeMethod: hardreset
mergeUnstable: true
label: ":arrow_heading_down: pull"
conflictLabel: "merge-conflict"
+39
View File
@@ -0,0 +1,39 @@
<!--
Thank you for contributing to DeepTutor! 🚀
Please ensure your PR is ready for review and follows our contribution guidelines.
For more details, see our [CONTRIBUTING.md](https://github.com/HKUDS/DeepTutor/blob/dev/CONTRIBUTING.md).
-->
### Description
*A clear and concise description of the changes.*
### Related Issues
- Closes #...
- Related to #...
### Module(s) Affected
- [ ] `agents`
- [ ] `api`
- [ ] `config`
- [ ] `core`
- [ ] `knowledge`
- [ ] `logging`
- [ ] `services`
- [ ] `tools`
- [ ] `utils`
- [ ] `web` (Frontend)
- [ ] `docs` (Documentation)
- [ ] `scripts`
- [ ] `tests`
- [ ] Other: `...`
### Checklist
- [ ] I have read and followed the [contribution guidelines](https://github.com/HKUDS/DeepTutor/blob/dev/CONTRIBUTING.md).
- [ ] My code follows the project's coding standards.
- [ ] I have run `pre-commit run --all-files` and fixed any issues.
- [ ] I have added relevant tests for my changes.
- [ ] I have updated the documentation (if necessary).
- [ ] My changes do not introduce any new security vulnerabilities.
### Additional Notes
*Add any other context or screenshots about the pull request here.*
+70
View File
@@ -0,0 +1,70 @@
name: Docker Release
# Triggered when a GitHub Release is published.
# Builds a multi-platform Docker image and pushes it to GitHub Container Registry (GHCR).
#
# Image: ghcr.io/hkuds/deeptutor
# Tags:
# - Version tag stripped of 'v' prefix (e.g. release v1.2.3 → image tag 1.2.3)
# - latest (always points to the most recently published release)
#
# Platforms: linux/amd64, linux/arm64
on:
release:
types: [published]
permissions:
contents: read
packages: write
jobs:
build-and-push:
name: Build and Push Multi-Platform Docker Image
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
# Required for linux/arm64 cross-compilation on GitHub-hosted ubuntu runners
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
# Enable BuildKit with multi-platform build support
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Log in to GitHub Container Registry
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
# Extract tags from the release:
# type=semver strips the leading 'v' (v1.2.3 → 1.2.3)
# type=raw adds a 'latest' tag on every published release
- name: Extract Docker metadata
id: meta
uses: docker/metadata-action@v5
with:
images: ghcr.io/hkuds/deeptutor
tags: |
type=semver,pattern={{version}}
type=raw,value=latest
- name: Build and push
uses: docker/build-push-action@v6
with:
context: .
file: ./Dockerfile
target: production
platforms: linux/amd64,linux/arm64
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
# Use GitHub Actions cache to speed up repeated builds
# mode=max caches all intermediate layers (frontend-builder and python-base are expensive)
cache-from: type=gha
cache-to: type=gha,mode=max
+154
View File
@@ -0,0 +1,154 @@
name: PyPI Release
# Triggered when a GitHub Release is published.
# Publishes the full app package with the version derived from the release tag:
# - deeptutor (Python backend/CLI + packaged Next.js standalone assets)
#
# The CLI-only package is intentionally not published to PyPI; install it from
# a local checkout with `python -m pip install -e ./packaging/deeptutor-cli`.
#
# Expected tag format: vMAJOR.MINOR.PATCH, with PEP 440-compatible suffixes allowed.
# Example: GitHub release tag v1.3.10 -> PyPI version 1.3.10.
#
# PyPI authentication uses Trusted Publishing. Configure the `deeptutor` PyPI
# project to trust this workflow file, then no API token secret is needed.
on:
release:
types: [published]
permissions:
contents: read
id-token: write
concurrency:
group: pypi-release-${{ github.event.release.tag_name }}
cancel-in-progress: false
jobs:
build-and-publish:
name: Build and Publish PyPI Package
runs-on: ubuntu-latest
environment:
name: pypi
url: https://pypi.org/project/deeptutor/
steps:
- name: Checkout release tag
uses: actions/checkout@v4
with:
ref: ${{ github.event.release.tag_name }}
fetch-depth: 0
- name: Verify release tag is on main
shell: bash
run: |
set -euo pipefail
git fetch origin main:refs/remotes/origin/main --no-tags
tag="${{ github.event.release.tag_name }}"
tag_commit="$(git rev-list -n 1 "$tag")"
if ! git merge-base --is-ancestor "$tag_commit" origin/main; then
echo "Release tag $tag ($tag_commit) is not on origin/main; refusing to publish to PyPI." >&2
exit 1
fi
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: "3.11"
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: "22"
cache: npm
cache-dependency-path: web/package-lock.json
- name: Install build tools
run: |
python -m pip install --upgrade pip
python -m pip install --upgrade build packaging twine
- name: Verify release tag matches deeptutor/__version__.py
id: version
shell: bash
run: |
set -euo pipefail
python - <<'PY'
import os
import re
from pathlib import Path
from packaging.version import Version
tag = os.environ["RELEASE_TAG"]
tag_raw = tag[1:] if tag.startswith("v") else tag
tag_version = str(Version(tag_raw))
src = Path("deeptutor/__version__.py").read_text(encoding="utf-8")
match = re.search(r'^__version__\s*=\s*"([^"]+)"', src, re.MULTILINE)
if not match:
raise SystemExit(
"Could not find __version__ in deeptutor/__version__.py"
)
code_version = str(Version(match.group(1)))
if code_version != tag_version:
raise SystemExit(
f"Release tag {tag!r} (normalized {tag_version!r}) does not "
f"match deeptutor/__version__.py value {code_version!r}. "
"Bump __version__ before tagging."
)
with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as handle:
handle.write(f"version={code_version}\n")
PY
env:
RELEASE_TAG: ${{ github.event.release.tag_name }}
- name: Install frontend dependencies
working-directory: web
run: npm ci --legacy-peer-deps
- name: Build packaged Web assets
run: python scripts/prepare_web_package.py
env:
NEXT_PUBLIC_API_BASE: __NEXT_PUBLIC_API_BASE_PLACEHOLDER__
NEXT_PUBLIC_AUTH_ENABLED: __NEXT_PUBLIC_AUTH_ENABLED_PLACEHOLDER__
- name: Build distributions
shell: bash
run: |
set -euo pipefail
mkdir -p dist/deeptutor
# Run from /tmp so any repository-local build/ directory cannot shadow
# PyPA's `build` module during repeated package builds.
# Wheels are the supported public install artifacts. The full app
# wheel contains packaged Next.js assets; source distributions would
# either duplicate those large assets or require a frontend build.
(cd /tmp && python -m build --wheel --outdir "$GITHUB_WORKSPACE/dist/deeptutor" "$GITHUB_WORKSPACE")
- name: Verify package metadata
run: |
python -m twine check dist/deeptutor/*
python - <<'PY'
from pathlib import Path
expected = "${{ steps.version.outputs.version }}"
files = {
"deeptutor": sorted(path.name for path in Path("dist/deeptutor").glob("*")),
}
for package, names in files.items():
print(package)
print("\n".join(f" {name}" for name in names))
required = [
("deeptutor", f"deeptutor-{expected}-py3-none-any.whl"),
]
missing = [name for package, name in required if name not in files[package]]
if missing:
raise SystemExit(f"Missing expected distributions: {missing}")
PY
- name: Publish deeptutor to PyPI
uses: pypa/gh-action-pypi-publish@release/v1
with:
packages-dir: dist/deeptutor/
print-hash: true
+202
View File
@@ -0,0 +1,202 @@
name: Tests
on:
push:
branches:
- main
- dev
paths:
- "deeptutor/**"
- "deeptutor_cli/**"
- "tests/**"
- "requirements/**"
- "requirements.txt"
- "pyproject.toml"
- "web/**"
- ".github/workflows/tests.yml"
pull_request:
branches:
- main
- dev
paths:
- "deeptutor/**"
- "deeptutor_cli/**"
- "tests/**"
- "requirements/**"
- "requirements.txt"
- "pyproject.toml"
- "web/**"
- ".github/workflows/tests.yml"
jobs:
lint:
name: Lint and Format
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: "3.11"
- name: Install lint tools
run: |
python -m pip install --upgrade pip
pip install ruff
- name: Run Ruff lint
run: ruff check .
- name: Run Ruff format check
run: ruff format --check .
web-tests:
name: Web Node Tests
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: "22"
cache: npm
cache-dependency-path: web/package-lock.json
- name: Install frontend dependencies
working-directory: web
run: npm ci --legacy-peer-deps
- name: Run frontend node tests
working-directory: web
run: npm run test:node
import-check:
name: Import Check (Python ${{ matrix.python-version }})
runs-on: ubuntu-latest
continue-on-error: ${{ matrix.experimental == true }}
strategy:
fail-fast: false
matrix:
python-version: ["3.11", "3.12", "3.13"]
experimental: [false]
include:
- python-version: "3.14"
experimental: true
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
- name: Cache pip packages
uses: actions/cache@v4
with:
path: ~/.cache/pip
key: ${{ runner.os }}-pip-${{ matrix.python-version }}-${{ hashFiles('requirements/server.txt', 'requirements/cli.txt') }}
restore-keys: |
${{ runner.os }}-pip-${{ matrix.python-version }}-
- name: Install minimal dependencies for import check
run: |
python -m pip install --upgrade pip
pip install -r requirements/server.txt
- name: Check module imports
run: |
echo "🐍 Testing with Python ${{ matrix.python-version }}"
python -c "from deeptutor.runtime.orchestrator import ChatOrchestrator; print('✅ Orchestrator imports OK')"
python -c "from deeptutor.runtime.registry.tool_registry import get_tool_registry; print('✅ Tool registry imports OK')"
python -c "from deeptutor.runtime.registry.capability_registry import get_capability_registry; print('✅ Capability registry imports OK')"
python -c "from deeptutor.services.config.runtime_settings import RuntimeSettingsService; print('✅ RuntimeSettingsService imports OK')"
python -c "from deeptutor.api.routers.unified_ws import unified_websocket; print('✅ Unified WS imports OK')"
python -c "from deeptutor.services.prompt.manager import PromptManager; print('✅ Prompt manager imports OK')"
python -c "from deeptutor.logging import configure_logging, bind_log_context, capture_process_logs, ProcessLogEvent; print('✅ Logging imports OK')"
env:
PYTHONPATH: ${{ github.workspace }}
python-tests:
name: Python Tests (Python ${{ matrix.python-version }})
runs-on: ubuntu-latest
needs: import-check
continue-on-error: ${{ matrix.experimental == true }}
strategy:
fail-fast: false
matrix:
python-version: ["3.11", "3.12", "3.13"]
experimental: [false]
include:
- python-version: "3.14"
experimental: true
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
- name: Cache pip packages
uses: actions/cache@v4
with:
path: ~/.cache/pip
key: ${{ runner.os }}-pip-${{ matrix.python-version }}-${{ hashFiles('requirements/server.txt', 'requirements/cli.txt', 'requirements/partners.txt') }}
restore-keys: |
${{ runner.os }}-pip-${{ matrix.python-version }}-
- name: Install smoke test dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements/server.txt
pip install -r requirements/partners.txt
pip install pytest pytest-asyncio
- name: Create minimal runtime config
run: |
mkdir -p data/user/settings
cat > data/user/settings/main.yaml <<'YAML'
system:
language: en
logging:
level: WARNING
YAML
- name: Run Python tests
run: |
echo "🧪 Running Python tests on Python ${{ matrix.python-version }}"
pytest -q tests deeptutor/learning/tests
env:
PYTHONPATH: ${{ github.workspace }}
test-summary:
name: Test Summary
runs-on: ubuntu-latest
needs: [lint, web-tests, import-check, python-tests]
if: always()
steps:
- name: Check test results
run: |
echo "## 🧪 Test Results Summary" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "| Check | Status |" >> $GITHUB_STEP_SUMMARY
echo "|-------|--------|" >> $GITHUB_STEP_SUMMARY
echo "| Lint and format | ${{ needs.lint.result == 'success' && '✅ Passed' || '❌ Failed' }} |" >> $GITHUB_STEP_SUMMARY
echo "| Web node tests | ${{ needs.web-tests.result == 'success' && '✅ Passed' || '❌ Failed' }} |" >> $GITHUB_STEP_SUMMARY
echo "| Import check (3.11/3.12/3.13; 3.14 best-effort) | ${{ needs.import-check.result == 'success' && '✅ Passed' || '❌ Failed' }} |" >> $GITHUB_STEP_SUMMARY
echo "| Python tests (3.11/3.12/3.13; 3.14 best-effort) | ${{ needs.python-tests.result == 'success' && '✅ Passed' || '❌ Failed' }} |" >> $GITHUB_STEP_SUMMARY
- name: Fail if tests failed
if: needs.lint.result == 'failure' || needs.web-tests.result == 'failure' || needs.import-check.result == 'failure' || needs.python-tests.result == 'failure'
run: exit 1
+313
View File
@@ -0,0 +1,313 @@
# ============================================
# AI-Tutor Project .gitignore
# ============================================
# ============================================
# User Generated Data and Outputs
# ============================================
# Runtime data (knowledge bases, tutorbot workspaces, memory, etc.)
data/
/multi-user/
run_code_workspace/
deeptutor/agents/question/reference_papers/
deeptutor/services/rag/eg_only_for_analysis/
/docs/
/site/
.claude
.agents/
# LaTeX build artifacts
*.aux
*.bbl
*.blg
*.fdb_latexmk
*.fls
*.out
*.synctex.gz
*.pdf
!demo/*.pdf
# ============================================
# Python Related
# ============================================
# Bytecode cache
__pycache__/
**/__pycache__/
*.py[cod]
*$py.class
*.so
# Distribution/Packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# Virtual Environments
.env
*.env
*.env.local
env/
venv/
ENV/
.venv/
env.bak/
venv.bak/
# ============================================
# Node.js and Frontend Build
# ============================================
# Node modules
node_modules/
**/node_modules/
# Next.js build output
.next/
web/.next/
out/
web/out/
.vercel/
**/.vercel/
.turbo/
**/.turbo/
# Auto-generated env.local (created by start_web.py / start_tour.py)
web/.env.local
# Frontend build artifacts
dist/
web/dist/
build/
web/build/
.open-next/
**/.open-next/
.wrangler/
**/.wrangler/
.vite/
**/.vite/
# Yarn / Plug'n'Play
.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions
# TypeScript build info
*.tsbuildinfo
# ============================================
# Common Output and Cache Directories
# ============================================
# Output directories
output/
outputs/
**/output/
**/outputs/
# Cache directories
cache/
**/cache/
.cache/
.ruff_cache
.playwright-cli/
# Log files
*.log
# ============================================
# IDE and Editors
# ============================================
# VSCode
.vscode/
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
# Cursor
.cursor/
# PyCharm / IntelliJ IDEA
.idea/
*.iml
*.iws
*.ipr
# Sublime Text
*.sublime-project
*.sublime-workspace
# Vim
*.swp
*.swo
*~
.netrwhist
# Emacs
*~
\#*\#
/.emacs.desktop
/.emacs.desktop.lock
*.elc
auto-save-list
tramp
.\#*
# ============================================
# Operating System Files
# ============================================
# macOS
.DS_Store
.AppleDouble
.LSOverride
Icon
._*
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
# Windows
Thumbs.db
Thumbs.db:encryptable
ehthumbs.db
ehthumbs_vista.db
*.stackdump
[Dd]esktop.ini
$RECYCLE.BIN/
*.cab
*.msi
*.msix
*.msm
*.msp
*.lnk
# Linux
*~
.fuse_hidden*
.directory
.Trash-*
.nfs*
# ============================================
# Temporary Files
# ============================================
*.tmp
*.temp
*.bak
*.backup
*.swp
*.swo
# Local scripts
启动 DeepTutor.bat
# ============================================
# Testing and Coverage
# ============================================
.coverage
.coverage.*
htmlcov/
.pytest_cache/
.pytest_tmp/
.tox/
nosetests.xml
coverage.xml
develop/
# ============================================
# Jupyter Notebook
# ============================================
.ipynb_checkpoints
*.ipynb_checkpoints/
# ============================================
# Type Checking
# ============================================
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# ============================================
# Other Python Tools
# ============================================
# Celery
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# ============================================
# Profiling
# ============================================
*.prof
*.pstats
# ============================================
# Database Files
# ============================================
*.db
*.sqlite
*.sqlite3
# ============================================
# Compressed Files
# ============================================
*.zip
*.tar
*.tar.gz
*.rar
*.7z
# ============================================
# Reference Papers (large binary files)
# ============================================
# Keep structure but ignore large PDFs in reference_papers
# question_agents/reference_papers/**/*.pdf
# ============================================
# Audio/Video Output (TTS generated)
# ============================================
*.mp3
*.wav
*.ogg
!demo/*.mp4
+106
View File
@@ -0,0 +1,106 @@
# Pre-commit hooks configuration for AI-Tutor project
# This configuration ensures code quality and consistency across the team
#
# Installation:
# pip install pre-commit
# pre-commit install
#
# Usage:
# pre-commit run --all-files # Run on all files
# git commit # Hooks run automatically on commit
repos:
# ============================================
# General file checks
# ============================================
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v6.0.0
hooks:
- id: trailing-whitespace
args: [--markdown-linebreak-ext=md]
exclude: ^(assets/roster/.*\.svg|.*\.min\.(js|css)|.*\.lock|.*\.log|.*\.pdf|.*\.zip|.*\.tar\.gz)
- id: end-of-file-fixer
exclude: ^(assets/roster/.*\.svg|.*\.min\.(js|css)|.*\.lock|.*\.log|.*\.pdf|.*\.zip|.*\.tar\.gz)
- id: check-yaml
args: [--unsafe]
- id: check-json
exclude: ^(.*\.lock|.*\.log)
- id: check-added-large-files
args: [--maxkb=6144]
- id: check-merge-conflict
- id: check-case-conflict
- id: check-toml
# ============================================
# Python code formatting and linting
# ============================================
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.14.7
hooks:
- id: ruff
# Added --quiet to suppress logs; --exit-zero makes it a "soft fail" if desired
args: [--fix, --quiet, --exit-zero]
- id: ruff-format
args: [--quiet]
# ============================================
# Frontend code formatting and linting
# ============================================
- repo: https://github.com/pre-commit/mirrors-prettier
rev: v4.0.0-alpha.8
hooks:
- id: prettier
args: [--log-level, warn]
files: ^web/.*\.(css|scss|json|jsonc|yaml|yml|md|graphql|html|ts|tsx|js|jsx)$
exclude: ^web/(node_modules|\.next|out|dist|build)/
# ============================================
# Security checks
# ============================================
- repo: https://github.com/Yelp/detect-secrets
rev: v1.5.0
hooks:
- id: detect-secrets
args: ['--baseline', '.secrets.baseline']
exclude: package-lock.json
pass_filenames: false
# Replaced Safety with pip-audit due to version 3.x breakdown
# NOTE: pip-audit disabled due to pip-api upstream bug with non-ASCII paths on Windows
# (UnicodeDecodeError when username contains Chinese characters)
# See: https://github.com/di/pip-api/issues/123
# - repo: https://github.com/pypa/pip-audit
# rev: v2.7.3
# hooks:
# - id: pip-audit
# args: ["--desc", "on"]
- repo: https://github.com/PyCQA/bandit
rev: 1.8.0
hooks:
- id: bandit
args: [-c, pyproject.toml, -q]
exclude: ^tests/
additional_dependencies: ["bandit[toml]"]
# ============================================
# Type checking
# ============================================
# Type checking - currently relaxed due to gradual type adoption
# TODO: Gradually enable stricter checks as types are added
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.13.0
hooks:
- id: mypy
args: [--ignore-missing-imports, --no-error-summary, --no-strict-optional]
exclude: ^(tests/|scripts/|deeptutor/agents/|deeptutor/services/rag/|deeptutor/api/routers/)
additional_dependencies:
- types-PyYAML
- types-requests
- types-croniter
+377
View File
@@ -0,0 +1,377 @@
{
"version": "1.5.0",
"plugins_used": [
{
"name": "ArtifactoryDetector"
},
{
"name": "AWSKeyDetector"
},
{
"name": "AzureStorageKeyDetector"
},
{
"name": "Base64HighEntropyString",
"limit": 4.5
},
{
"name": "BasicAuthDetector"
},
{
"name": "CloudantDetector"
},
{
"name": "DiscordBotTokenDetector"
},
{
"name": "GitHubTokenDetector"
},
{
"name": "GitLabTokenDetector"
},
{
"name": "HexHighEntropyString",
"limit": 3.0
},
{
"name": "IbmCloudIamDetector"
},
{
"name": "IbmCosHmacDetector"
},
{
"name": "IPPublicDetector"
},
{
"name": "JwtTokenDetector"
},
{
"name": "KeywordDetector",
"keyword_exclude": ""
},
{
"name": "MailchimpDetector"
},
{
"name": "NpmDetector"
},
{
"name": "OpenAIDetector"
},
{
"name": "PrivateKeyDetector"
},
{
"name": "PypiTokenDetector"
},
{
"name": "SendGridDetector"
},
{
"name": "SlackDetector"
},
{
"name": "SoftlayerDetector"
},
{
"name": "SquareOAuthDetector"
},
{
"name": "StripeDetector"
},
{
"name": "TelegramBotTokenDetector"
},
{
"name": "TwilioKeyDetector"
}
],
"filters_used": [
{
"path": "detect_secrets.filters.allowlist.is_line_allowlisted"
},
{
"path": "detect_secrets.filters.common.is_ignored_due_to_verification_policies",
"min_level": 2
},
{
"path": "detect_secrets.filters.heuristic.is_indirect_reference"
},
{
"path": "detect_secrets.filters.heuristic.is_likely_id_string"
},
{
"path": "detect_secrets.filters.heuristic.is_lock_file"
},
{
"path": "detect_secrets.filters.heuristic.is_not_alphanumeric_string"
},
{
"path": "detect_secrets.filters.heuristic.is_potential_uuid"
},
{
"path": "detect_secrets.filters.heuristic.is_prefixed_with_dollar_sign"
},
{
"path": "detect_secrets.filters.heuristic.is_sequential_string"
},
{
"path": "detect_secrets.filters.heuristic.is_swagger_file"
},
{
"path": "detect_secrets.filters.heuristic.is_templated_secret"
}
],
"results": {
".env.example_CN": [
{
"type": "Secret Keyword",
"filename": ".env.example_CN",
"hashed_secret": "ec417f567082612f8fd6afafe1abcab831fca840",
"is_verified": false,
"line_number": 19
}
],
"deeptutor/agents/guide/agents/interactive_agent.py": [
{
"type": "Base64 High Entropy String",
"filename": "deeptutor/agents/guide/agents/interactive_agent.py",
"hashed_secret": "559f33e318ea8360e316ec7409de63272a7daea0",
"is_verified": false,
"line_number": 88
},
{
"type": "Base64 High Entropy String",
"filename": "deeptutor/agents/guide/agents/interactive_agent.py",
"hashed_secret": "fe9ae166dc80168f37e50564be9e45c016a48cd0",
"is_verified": false,
"line_number": 89
},
{
"type": "Base64 High Entropy String",
"filename": "deeptutor/agents/guide/agents/interactive_agent.py",
"hashed_secret": "482f1d4d250823ce0ff5fad9dfaf0d471835aedb",
"is_verified": false,
"line_number": 90
}
],
"deeptutor/agents/solve/main_solver.py": [
{
"type": "Secret Keyword",
"filename": "deeptutor/agents/solve/main_solver.py",
"hashed_secret": "985b05576c57bdeccfcaf33261ea1c43ce7e3155",
"is_verified": false,
"line_number": 184
}
],
"deeptutor/api/routers/system.py": [
{
"type": "Secret Keyword",
"filename": "deeptutor/api/routers/system.py",
"hashed_secret": "985b05576c57bdeccfcaf33261ea1c43ce7e3155",
"is_verified": false,
"line_number": 160
}
],
"deeptutor/services/config/provider_runtime.py": [
{
"type": "Secret Keyword",
"filename": "deeptutor/services/config/provider_runtime.py",
"hashed_secret": "985b05576c57bdeccfcaf33261ea1c43ce7e3155",
"is_verified": false,
"line_number": 331
}
],
"deeptutor/services/search/base.py": [
{
"type": "Secret Keyword",
"filename": "deeptutor/services/search/base.py",
"hashed_secret": "8ee9d3cc35862a8ad26f9e27fb60db0e22ffe145",
"is_verified": false,
"line_number": 18
}
],
"tests/agents/test_base_agent_binding.py": [
{
"type": "Secret Keyword",
"filename": "tests/agents/test_base_agent_binding.py",
"hashed_secret": "e9a5f12a8ecbb3eb46eca5096b5c52aa5e7c9fdd",
"is_verified": false,
"line_number": 18
}
],
"tests/core/test_builtin_tools.py": [
{
"type": "Secret Keyword",
"filename": "tests/core/test_builtin_tools.py",
"hashed_secret": "a62f2225bf70bfaccbc7f1ef2a397836717377de",
"is_verified": false,
"line_number": 188
}
],
"tests/services/config/test_embedding_runtime.py": [
{
"type": "Secret Keyword",
"filename": "tests/services/config/test_embedding_runtime.py",
"hashed_secret": "9aaa910eb49fa1f278c7288f0fa6001c16965716",
"is_verified": false,
"line_number": 68
},
{
"type": "Secret Keyword",
"filename": "tests/services/config/test_embedding_runtime.py",
"hashed_secret": "985b05576c57bdeccfcaf33261ea1c43ce7e3155",
"is_verified": false,
"line_number": 134
},
{
"type": "Secret Keyword",
"filename": "tests/services/config/test_embedding_runtime.py",
"hashed_secret": "e9a5f12a8ecbb3eb46eca5096b5c52aa5e7c9fdd",
"is_verified": false,
"line_number": 144
},
{
"type": "Secret Keyword",
"filename": "tests/services/config/test_embedding_runtime.py",
"hashed_secret": "8c895e1fc99e38655efea259aaa5510bde46b81c",
"is_verified": false,
"line_number": 182
}
],
"tests/services/config/test_provider_runtime.py": [
{
"type": "Secret Keyword",
"filename": "tests/services/config/test_provider_runtime.py",
"hashed_secret": "b07bfd6660c8a5e8f47ed4967498d25f095cb7c5",
"is_verified": false,
"line_number": 95
},
{
"type": "Secret Keyword",
"filename": "tests/services/config/test_provider_runtime.py",
"hashed_secret": "1e8f4accfda4813178f4f6317c767a915bfbf227",
"is_verified": false,
"line_number": 115
},
{
"type": "Secret Keyword",
"filename": "tests/services/config/test_provider_runtime.py",
"hashed_secret": "985b05576c57bdeccfcaf33261ea1c43ce7e3155",
"is_verified": false,
"line_number": 163
}
],
"tests/services/embedding/test_client_runtime.py": [
{
"type": "Secret Keyword",
"filename": "tests/services/embedding/test_client_runtime.py",
"hashed_secret": "e9a5f12a8ecbb3eb46eca5096b5c52aa5e7c9fdd",
"is_verified": false,
"line_number": 35
}
],
"tests/services/llm/test_config_module.py": [
{
"type": "Secret Keyword",
"filename": "tests/services/llm/test_config_module.py",
"hashed_secret": "6b8f36db289d14c3c7ba1bb21147b7a4fa7e7536",
"is_verified": false,
"line_number": 40
},
{
"type": "Secret Keyword",
"filename": "tests/services/llm/test_config_module.py",
"hashed_secret": "3acfb2c2b433c0ea7ff107e33df91b18e52f960f",
"is_verified": false,
"line_number": 102
}
],
"tests/services/llm/test_factory_provider_exec.py": [
{
"type": "Secret Keyword",
"filename": "tests/services/llm/test_factory_provider_exec.py",
"hashed_secret": "6b8f36db289d14c3c7ba1bb21147b7a4fa7e7536",
"is_verified": false,
"line_number": 15
},
{
"type": "Secret Keyword",
"filename": "tests/services/llm/test_factory_provider_exec.py",
"hashed_secret": "9247e92e3d5c3957c5f5480ec8917b9100baa32d",
"is_verified": false,
"line_number": 41
},
{
"type": "Secret Keyword",
"filename": "tests/services/llm/test_factory_provider_exec.py",
"hashed_secret": "627a27ae52d38269376e0117355fefc891b60334",
"is_verified": false,
"line_number": 84
}
],
"tests/services/test_model_catalog.py": [
{
"type": "Secret Keyword",
"filename": "tests/services/test_model_catalog.py",
"hashed_secret": "f2bb1f20475e99c2af44a6f6844c1329bea9d3d2",
"is_verified": false,
"line_number": 89
},
{
"type": "Secret Keyword",
"filename": "tests/services/test_model_catalog.py",
"hashed_secret": "21729167f484c69c93d2a1956dace832faee1e6a",
"is_verified": false,
"line_number": 107
},
{
"type": "Secret Keyword",
"filename": "tests/services/test_model_catalog.py",
"hashed_secret": "3090ca86558e326f27cb6f36d0592ed339f108be",
"is_verified": false,
"line_number": 141
},
{
"type": "Secret Keyword",
"filename": "tests/services/test_model_catalog.py",
"hashed_secret": "c02d46771666140734db6f2e650f2b051f448aad",
"is_verified": false,
"line_number": 146
}
],
"tests/test_openrouter_provider.py": [
{
"type": "Secret Keyword",
"filename": "tests/test_openrouter_provider.py",
"hashed_secret": "3acfb2c2b433c0ea7ff107e33df91b18e52f960f",
"is_verified": false,
"line_number": 10
}
],
"web/app/(workspace)/guide/hooks/useKaTeXInjection.ts": [
{
"type": "Base64 High Entropy String",
"filename": "web/app/(workspace)/guide/hooks/useKaTeXInjection.ts",
"hashed_secret": "559f33e318ea8360e316ec7409de63272a7daea0",
"is_verified": false,
"line_number": 25
},
{
"type": "Base64 High Entropy String",
"filename": "web/app/(workspace)/guide/hooks/useKaTeXInjection.ts",
"hashed_secret": "fe9ae166dc80168f37e50564be9e45c016a48cd0",
"is_verified": false,
"line_number": 27
},
{
"type": "Base64 High Entropy String",
"filename": "web/app/(workspace)/guide/hooks/useKaTeXInjection.ts",
"hashed_secret": "482f1d4d250823ce0ff5fad9dfaf0d471835aedb",
"is_verified": false,
"line_number": 29
}
]
},
"generated_at": "2026-04-06T16:37:14Z"
}
+138
View File
@@ -0,0 +1,138 @@
# DeepTutor — Agent-Native Architecture
## Overview
DeepTutor is an **agent-native** intelligent learning companion organized
around a two-layer plugin model — single-shot **Tools** invoked by the
LLM, and multi-stage **Capabilities** that take over a turn — exposed
through three entry points: CLI, WebSocket API, and Python SDK.
## Architecture
```
Entry Points: CLI (Typer) | WebSocket /api/v1/ws | Python SDK
↓ ↓ ↓
┌─────────────────────────────────────────────────┐
│ ChatOrchestrator │
│ routes UnifiedContext → selected Capability │
│ (defaults to `chat`) │
└──────────┬──────────────┬───────────────────────┘
│ │
┌──────────▼──┐ ┌────────▼──────────┐
│ ToolRegistry │ │ CapabilityRegistry │
│ (Level 1) │ │ (Level 2) │
└──────────────┘ └────────────────────┘
```
All capabilities emit on a shared `StreamBus`; the orchestrator fans
events out to consumers. Runtime settings live in
`data/user/settings/*.json` — project-root `.env` files are intentionally
ignored.
### Level 1 — Tools
Single-function tools the LLM picks on demand. Four user-toggleable tools
surface in `/settings/tools`:
| Tool | Description |
| -------------- | --------------------------------------------- |
| `brainstorm` | Breadth-first idea exploration with rationale |
| `web_search` | Web search with citations |
| `paper_search` | arXiv preprint search |
| `reason` | Dedicated deep-reasoning LLM call |
The rest are **context-gated**: the chat capability auto-mounts them from
`ToolMountFlags` (presence of a KB, attachments, sandbox availability, …), and
any of them can also be force-enabled via `--tool`. Auto-mounted set: `rag`,
`read_source`, `read_memory`, `write_memory`, `read_skill`, `load_tools`,
`exec`, `code_execution` (sandboxed Python: NL intent → code → run),
`list_notebook`, `write_note`, `web_fetch`, `github`, `cron`,
`ask_user` (pauses the turn and resumes with the user's reply), plus the
mastery-path tools. `geogebra_analysis` is parked under
`COMING_SOON_TOOL_TYPES`.
### Level 2 — Capabilities
Multi-stage pipelines that own the turn:
| Capability | Stages |
| ---------------- | ----------------------------------------------------- |
| `chat` | exploring → responding (single agentic loop, default) |
| `mastery_path` | responding (Guided Learning — chat loop + mastery tools, gated per topic type) |
| `deep_solve` | planning → reasoning → writing |
| `deep_question` | ideation → generation |
| `deep_research` | rephrasing → decomposing → researching → reporting |
| `visualize` | analyzing → generating → reviewing (SVG / Chart.js / Mermaid / HTML; or routes to Manim sub-stages via `render_type`) |
| `math_animator` | concept_analysis → concept_design → code_generation → code_retry → summary → render_output |
All capabilities converge on `emit_capability_result()` in
`deeptutor/capabilities/_shared.py` so every turn emits the same envelope
(response payload + `cost_summary` from `UsageTracker`). Status copy and
prompts are i18n'd via `capabilities/prompts/{en,zh}/<name>.yaml`.
## CLI Usage
```bash
# Install
pip install deeptutor # Full app (CLI + Web/API + packaged Web assets)
pip install deeptutor-cli # CLI-only
# Run any capability
deeptutor run chat "Explain Fourier transform"
deeptutor run deep_solve "Solve x^2=4" -t rag --kb my-kb
deeptutor run visualize "Animate sine wave" --config render_mode=manim_video
# Interactive REPL
deeptutor chat
# (inside the REPL: /regenerate or /retry re-runs the last user message)
# Partners (IM-connected companions)
deeptutor partner list
# Knowledge bases, memory, server
deeptutor kb list
deeptutor kb create my-kb --doc textbook.pdf
deeptutor memory show
deeptutor serve --port 8001 # API server only
deeptutor start # backend + frontend together
```
## Key Files
| Path | Purpose |
| ------------------------------------------ | ------------------------------------ |
| `deeptutor/runtime/orchestrator.py` | `ChatOrchestrator` — unified entry |
| `deeptutor/runtime/launcher.py` | Backend + frontend lifecycle / port discovery |
| `deeptutor/runtime/registry/` | Tool + Capability registries |
| `deeptutor/runtime/bootstrap/builtin_capabilities.py` | Built-in capability class paths |
| `deeptutor/services/config/runtime_settings.py` | JSON settings + process-env overrides |
| `deeptutor/core/stream.py`, `stream_bus.py` | StreamEvent protocol + async fan-out |
| `deeptutor/core/tool_protocol.py` | `BaseTool` + `ToolDefinition` |
| `deeptutor/core/capability_protocol.py` | `BaseCapability` + `CapabilityManifest` |
| `deeptutor/core/context.py` | `UnifiedContext` dataclass |
| `deeptutor/tools/builtin/__init__.py` | All built-in tool wrappers |
| `deeptutor/capabilities/` | Built-in capability implementations |
| `deeptutor/app.py` | `DeepTutorApp` — Python SDK facade |
| `deeptutor_cli/main.py` | Typer CLI entry point |
| `deeptutor/api/routers/unified_ws.py` | Unified WebSocket endpoint |
## Dependency Layers
Public install paths and source extras are defined in `pyproject.toml`.
Requirements files mirror the same dependency groups for Docker/CI installs.
```
pip install deeptutor — Full app (CLI + Web/API + packaged Web assets)
pip install deeptutor-cli — CLI-only (LLM + RAG + providers + document parsing)
pip install -e . — Source install for development
Source extras (.[ extra ], defined in pyproject.toml):
.[cli] — CLI-only dependency set
.[server] — Web/API server dependencies
.[partners] — Partner channel SDKs + MCP client (legacy alias: .[tutorbot])
.[matrix] — Matrix channel for Partners (matrix-nio; needs libolm)
.[matrix-e2e] — Matrix with end-to-end encryption (matrix-nio[e2e])
.[math-animator] — Manim addon (powers `visualize` Manim renders + `deeptutor run math_animator`)
.[dev] — Test / lint tooling
.[all] — Everything above
```
+38
View File
@@ -0,0 +1,38 @@
cff-version: 1.2.0
message: "If you use this software, please cite it as below."
title: "DeepTutor: Towards Agentic Personalized Tutoring"
authors:
- family-names: "Zhao"
given-names: "Bingxi"
- family-names: "Zhang"
given-names: "Jiahao"
- family-names: "Ren"
given-names: "Xubin"
- family-names: "Guo"
given-names: "Zirui"
- family-names: "Chu"
given-names: "Tianzhe"
- family-names: "Ma"
given-names: "Yi"
- family-names: "Huang"
given-names: "Chao"
preferred-citation:
type: article
title: "DeepTutor: Towards Agentic Personalized Tutoring"
authors:
- family-names: "Zhao"
given-names: "Bingxi"
- family-names: "Zhang"
given-names: "Jiahao"
- family-names: "Ren"
given-names: "Xubin"
- family-names: "Guo"
given-names: "Zirui"
- family-names: "Chu"
given-names: "Tianzhe"
- family-names: "Ma"
given-names: "Yi"
- family-names: "Huang"
given-names: "Chao"
journal: "arXiv preprint arXiv:2604.26962"
year: 2026
+389
View File
@@ -0,0 +1,389 @@
# DeepTutor Containerization
This document covers deploying DeepTutor from a container image: the
recommended `docker run` path, the hardened rootless-Podman path with a
read-only root filesystem, runtime configuration, the optional PocketBase
sidecar, and the security notes that motivate the default posture.
For PyPI / source installs, see the main [README.md](../README.md). This
file is only about running the published image.
---
## Overview
The published `ghcr.io/hkuds/deeptutor` image runs both the FastAPI
backend (`:8001`) and the Next.js frontend (`:3782`) under `supervisord`
inside a single container, on top of `python:3.11-slim`. There is one
data tree (`/app/data` inside the container) that holds settings,
workspaces, memory, knowledge bases, and logs. Bind-mount that tree to
the host to make state survive container restarts.
The image is built so it works under three deployment shapes:
1. **`docker run`** — the easy path. Rootful, writable rootfs, single
bind mount on `/app/data`.
2. **`docker compose`** (`docker-compose.yml`) — same image plus the
PocketBase sidecar and the sandbox-runner sidecar. Still rootful,
writable rootfs.
3. **`podman compose -f compose.yaml`** — the hardened path. Rootless
(`userns_mode: keep-id`), read-only rootfs, tmpfs in place of writable
system dirs, bind mount on `./data`.
The architectural change that makes shape 3 work is that URL knowledge
no longer lives in the frontend bundle. Concretely:
- The bundle is built with no `NEXT_PUBLIC_API_BASE` placeholder and no
`sed -i` of the build output. `web/lib/api.ts` exports `apiUrl` and
`wsUrl` as one-line pass-throughs, so the browser fetches relative
paths through the frontend (`:3782/api/...`).
- `web/proxy.ts` catches `/api/*` and `/ws/*` and rewrites them to
`DEEPTUTOR_API_BASE_URL` at request time. That env var is set by the
container entrypoint on every start, read from
`data/user/settings/system.json`.
- `start-frontend.sh` is now 12 lines: it sets `PORT`/`HOSTNAME` and
`exec`s `node /app/web/server.js`. No mutations of the bundle.
- `supervisord` runs as root (PID 1) and drops each program (backend,
frontend) to a non-root `deeptutor` user (UID 1000) via its per-program
`user=` directive, so the app processes stay non-root. With
`userns_mode: keep-id` on the host that UID maps to your host UID; with a
regular `docker run` it's a normal unprivileged user inside the container.
The full per-installation guide follows.
---
## Docker (default)
The simplest possible deployment. One container, one volume, two port
mappings.
```bash
docker run --rm --name deeptutor \
-p 127.0.0.1:3782:3782 \
-v deeptutor-data:/app/data \
ghcr.io/hkuds/deeptutor:latest
```
Open <http://127.0.0.1:3782>. The container creates
`/app/data/user/settings/*.json` on first boot; configure model providers
from the Web Settings page. Config, API keys, logs, workspace files,
memory, and knowledge bases persist in the `deeptutor-data` named volume.
Notes:
- **Only `3782` needs to be published.** The browser talks exclusively to
the frontend origin (`:3782`); all `/api/*` and `/ws/*` traffic is
forwarded to the FastAPI backend **inside the container** by the Next.js
middleware (`web/proxy.ts`), which reads `DEEPTUTOR_API_BASE_URL`
(`http://localhost:8001` by default) at request time. You do **not** need
to expose `:8001` to the host for the UI to work. Publishing `:8001`
(`-p 127.0.0.1:8001:8001`) is optional — handy only for hitting the API
directly (curl, scripts) or debugging.
- **Different host ports:** change the left side of each `-p host:container`
mapping (e.g. `-p 127.0.0.1:8088:3782`). If you change container-side
ports in `data/user/settings/system.json` (`backend_port`,
`frontend_port`), restart the container and update the right side of
each mapping to match.
- **Detached:** add `-d`, then `docker logs -f deeptutor` to follow,
`docker stop deeptutor` to stop, `docker rm deeptutor` before reusing
the name. The `deeptutor-data` volume keeps your settings and workspace
across restarts.
### Remote / reverse-proxy deployments
For the common **single-container** case (this image), you do **not** need
to configure an API base at all. The browser issues relative `/api/*` and
`/ws/*` requests against whatever origin serves the UI
(`https://deeptutor.example.com`), and the in-container Next.js middleware
forwards them to the backend on `localhost:8001`. Just point your reverse
proxy / TLS terminator at the published `:3782` and you're done.
You only need to set an API base for a **split deployment** where the
backend runs in a separate container. Edit `data/user/settings/system.json`
on the host (inside the `deeptutor-data` volume — `docker volume inspect
deeptutor-data` to find its mountpoint) and set the in-network address the
frontend container uses to reach the backend container:
```json
{
"next_public_api_base": "http://backend:8001"
}
```
The entrypoint reads this on every start and exports
`DEEPTUTOR_API_BASE_URL` for `proxy.ts` (precedence: `next_public_api_base`,
then `next_public_api_base_external`, then `http://localhost:8001`). Note
that because the proxy is **server-side**, `DEEPTUTOR_API_BASE_URL` is the
address the frontend *server* uses to reach the backend — not a URL the
browser ever sees. `public_api_base` is accepted as a compatibility alias
and normalized into `next_public_api_base_external` on save.
CORS uses frontend **origins**, not API URLs. With auth disabled,
DeepTutor permits normal HTTP/HTTPS browser origins by default. With
auth enabled, add exact frontend origins:
```json
{
"cors_origins": ["https://deeptutor.example.com"]
}
```
### Host LLM providers (Ollama / LM Studio / llama.cpp / vLLM / Lemonade)
Inside Docker, `localhost` is the container itself, not your host
machine. To reach a model service running on the host, use the host
gateway (recommended):
```bash
docker run --rm --name deeptutor \
-p 127.0.0.1:3782:3782 -p 127.0.0.1:8001:8001 \
--add-host=host.docker.internal:host-gateway \
-v deeptutor-data:/app/data \
ghcr.io/hkuds/deeptutor:latest
```
Then in **Settings → Models**, point the provider Base URL at
`host.docker.internal`:
- Ollama LLM: `http://host.docker.internal:11434/v1`
- Ollama embedding: `http://host.docker.internal:11434/api/embed`
- LM Studio: `http://host.docker.internal:1234/v1`
- llama.cpp: `http://host.docker.internal:8080/v1`
- Lemonade: `http://host.docker.internal:13305/api/v1`
Docker Desktop (macOS/Windows) usually resolves `host.docker.internal`
without `--add-host`. On Linux, the flag is the portable way.
**Linux alternative — host networking:** add `--network=host` and drop
the `-p` flags. The container shares the host network directly, so open
<http://127.0.0.1:3782> (or the `frontend_port` in `system.json`), and
host services can be reached with normal localhost URLs.
In host-network mode the processes bind directly on the host interfaces
(there is no `-p 127.0.0.1:` prefix to scope them). To keep them off the
LAN, set `BACKEND_HOST=127.0.0.1` and `FRONTEND_HOST=127.0.0.1` — they
override uvicorn's `--host` and Next.js's `HOSTNAME` (both default to
`0.0.0.0`). Only use these with `--network=host`: in bridge mode binding
to loopback breaks the published `-p` port forward.
---
## Podman / rootless / read-only rootfs
For users who want the strongest default posture — rootless, with a
read-only root filesystem — `compose.yaml` is the supported starting
point. It pulls the same `ghcr.io/hkuds/deeptutor:latest` image and
relies on the entrypoint chown + supervisord's per-program privilege drop,
the URL-forwarding `proxy.ts`, and host-side bind mounts to make it all work.
```bash
cp .env.example .env # then edit if needed
podman compose -f compose.yaml up -d
podman compose -f compose.yaml ps
podman compose -f compose.yaml logs -f deeptutor
```
Verify rootless is active (`podman info | grep -i rootless` should
report `true`).
What `compose.yaml` does, and why:
- **`read_only: true` on every service.** The container's rootfs is
read-only. The only writable surface is the `tmpfs:` mounts listed
per service plus the bind-mounted `./data` directory.
- **`userns_mode: keep-id`.** The container's UID 0 maps to your host
UID; the container's UID 1000 (the `deeptutor` user inside the image)
maps to your host UID 1000 (which most distros reserve for the first
human user). The `:U` suffix on every volume mount tells podman to
chown the bind-mount target to that mapped UID.
- **`tmpfs:` mounts for the system dirs the runtime expects to write.**
`/tmp` (Python/Node scratch), `/run` and `/var/run` (pidfiles),
`/var/log`, `/root`, `/home`. Sizes are intentionally generous; trim
to taste.
- **No named volumes.** Podman auto-creates named volumes with the
userns-mapped root (UID 100000), so 755 perms + wrong owner =
`PermissionError` on the first JSON write. Bind mounts on a host
directory you own work cleanly.
- **Loopback-only port bindings.** `127.0.0.1:` prefix on every `ports:`
entry. Drop the prefix to expose on all interfaces.
- **No sandbox-runner sidecar.** The `docker-compose.yml` shape includes
a hardened sidecar that runs untrusted model-generated code in a
least-privileged container. The podman shape does not — the main app
falls back to `bwrap` (Linux, if installed in the image) or the
restricted subprocess backend controlled by
`sandbox_allow_subprocess` in `system.json`.
### Running outside `compose.yaml`
`compose.yaml` is a starting point, not the only shape. The same
invariants apply if you want to drive `podman run` directly:
```bash
mkdir -p data/user/settings
echo '{}' > data/user/settings/system.json
podman run --rm -d --name deeptutor \
-p 127.0.0.1:8001:8001 \
-p 127.0.0.1:3782:3782 \
-v $(pwd)/data:/app/data:U \
--read-only \
--tmpfs /tmp:size=512m,mode=1777 \
--tmpfs /run:size=32m,mode=0755 \
--tmpfs /var/run:size=8m,mode=0755 \
--tmpfs /var/log:size=64m,mode=0755 \
--tmpfs /root:size=16m,mode=0700 \
--tmpfs /home:size=16m,mode=0755 \
--userns=keep-id \
ghcr.io/hkuds/deeptutor:latest
```
After the container is up, the backend and frontend always run as the
non-root `deeptutor` user (UID 1000) — `podman exec deeptutor ps -o user,pid,comm`
shows the `uvicorn`/`node` children as `deeptutor`. `supervisord` itself
(PID 1) runs as whatever UID the runtime started it with: root under rootful
Docker/Podman, or the host user under rootless podman + `userns_mode: keep-id`.
### Supervisord pidfile
The `[supervisord]` section carries **no `user=` directive**, so supervisord
runs as PID 1's UID and never tries to drop its own privilege; only its child
programs are dropped to `deeptutor` via the per-program `user=` directives.
Pinning `user=root` here (an earlier design) broke rootless keep-id, where
PID 1 is the non-root host user and lacks `CAP_SETUID`: supervisord refuses to
drop privilege and exits at startup with `Can't drop privilege as nonroot
user` (see supervisord's `options.py`).
The pidfile is written to **`/tmp/supervisord.pid`**. `/tmp` is `mode=1777`
(world-writable) in every run configuration above, so the pidfile is writable
whether PID 1 is root or the host UID, and regardless of who owns `/var/run`.
An earlier build pointed the pidfile at the root-owned `/var/run/supervisord.pid`;
under rootless keep-id the non-root PID 1 couldn't write it and logged a
cosmetic `CRIT could not write pidfile` on every start. Putting it in `/tmp`
removes that dependency on the `/var/run` owner and mode entirely.
---
## Runtime configuration
Almost everything you tune lives under `data/user/settings/` inside the
data tree. The container entrypoint unsets a list of related env vars
(`BACKEND_PORT`, `FRONTEND_PORT`, `NEXT_PUBLIC_API_BASE`,
`NEXT_PUBLIC_API_BASE_EXTERNAL`, `AUTH_ENABLED`, `POCKETBASE_URL`, etc.)
on every start and re-exports values from the JSONs. So: edit the JSONs,
restart, do **not** try to drive these with compose env vars.
| File | Purpose |
|:---|:---|
| `system.json` | Backend/frontend ports, public API base, CORS, SSL verification, attachment directory |
| `auth.json` | Optional auth toggle, username, password hash, token/cookie settings |
| `integrations.json` | Optional PocketBase and sidecar integration settings |
| `model_catalog.json` | LLM, embedding, and search provider profiles; API keys; active models |
| `interface.json` | UI language / theme / sidebar preferences |
| `main.yaml` | Runtime behavior defaults and path injection |
| `agents.yaml` | Capability/tool temperature and token settings |
The two settings most relevant to a fresh install:
- **`system.json``next_public_api_base`** (in-network) and
**`next_public_api_base_external`** (cloud/external override). The
entrypoint reads these and exports `DEEPTUTOR_API_BASE_URL`, which
`web/proxy.ts` consumes. `public_api_base` is accepted as a
compatibility alias and is normalized into
`next_public_api_base_external` on save.
- **`system.json``backend_port` / `frontend_port`**. The container
ports the supervisor binds inside the container. If you change these,
update the right side of every `-p host:container` mapping (or the
`HOST_PORT_*` env var that `compose.yaml` reads) to match.
Project-root `.env` files are intentionally ignored as application
config. The Web **Settings** page is the recommended editor for the
JSON/YAML files; deep links to each section live in the page sidebar.
---
## PocketBase
PocketBase is an optional auth + storage sidecar. Activate it by setting
`integrations.pocketbase_url` to `http://pocketbase:8090` in
`data/user/settings/integrations.json` and bringing the `pocketbase`
service up alongside the main `deeptutor` service. With it running, the
main app stores user accounts and sessions in PocketBase instead of
falling back to the SQLite single-user layout.
The `pocketbase` service in `compose.yaml` (and the corrected mount in
`docker-compose.yml`) bind-mounts three subdirectories of `./data`
`/pb_data`, `/pb_public`, `/pb_hooks` — matching the upstream
`ghcr.io/muchobien/pocketbase:latest` image's entrypoint, which uses
absolute paths. The earlier `docker-compose.yml` example mounted
`/pb/pb_data` and crashed on first start with
`mkdir /pb_data: read-only file system`; this PR fixes that.
PocketBase stays a single-user integration — keep
`integrations.pocketbase_url` blank for multi-user deployments unless
you've wired up an external user store.
---
## Troubleshooting
**`CRIT could not write pidfile /var/run/supervisord.pid` on container start.**
Only on images built before the pidfile moved to `/tmp/supervisord.pid`
(`mode=1777`, always writable); current images don't emit it. The supervised
children come up either way — the line was always cosmetic. Fix: pull a
current image (or, on an old one, set the `/var/run` tmpfs to `mode=1777`).
**Page loads but Settings says "Backend unreachable".** The UI reaches the
backend through the in-container proxy, not a host port, so this is almost
always a backend that failed to start (check `docker logs deeptutor` for the
`[program:backend]` lines) or a wrong `DEEPTUTOR_API_BASE_URL` in a split
deployment — **not** a missing `:8001` host mapping (which the UI does not
need).
**`Cannot connect to the Docker daemon` on a podman host.** Run
`systemctl --user start podman.socket` (rootless) or set
`DOCKER_HOST=unix:///run/user/$UID/podman/podman.sock` for the
`docker-compose` CLI to use the podman socket.
**`Permission denied` on first JSON write under a named volume.** This
is the userns-mapped root problem; switch to a bind mount on a host
directory you own, or use `:U` on the volume mount.
**`sed -i` errors on a fresh image.** There shouldn't be any — the
runtime no longer mutates the bundle. The URL is forwarded at request
time. If you see one, you are probably on an older image; pull
`ghcr.io/hkuds/deeptutor:latest` again.
**Settings page won't accept the API base URL.** Open
`data/user/settings/system.json` on the host and set
`next_public_api_base_external` directly. The page UI is wired to
`public_api_base` (the legacy alias) and the legacy field will be
renormalized on save.
---
## Security notes
- The image drops privileges to a non-root `deeptutor` user (UID 1000)
before starting `supervisord`. Anything that runs as root is the
entrypoint, the chown, and the env-var export.
- `read_only: true` plus `tmpfs:` for the expected writable system
directories means the container's root filesystem is immutable at
runtime. A process that tries to write outside the listed tmpfs
paths or the bind-mounted `./data` tree will fail.
- `userns_mode: keep-id` on the host means a container escape lands
with your host user's permissions, not root.
- The sandbox-runner sidecar (in `docker-compose.yml`, **not** in
`compose.yaml`) is the strongest posture for untrusted model-generated
code: a sandbox escape lands in a stripped, unprivileged container
with no app secrets, not in the main app. The podman shape trades that
for the rootless-podman shape; the main app falls back to `bwrap` or
the restricted subprocess backend controlled by
`sandbox_allow_subprocess`.
- Auth (`data/user/settings/auth.json``auth_enabled = true`) gates
`/api/*` and `/ws/*` via the `dt_token` cookie. `web/proxy.ts` reads
`DEEPTUTOR_AUTH_ENABLED` (exported by the entrypoint on every start)
to decide whether to require the cookie.
- CORS uses frontend **origins**, not API URLs. With auth enabled, set
`cors_origins` in `system.json` to the exact frontend origins the
deployment serves.
+220
View File
@@ -0,0 +1,220 @@
# Contributing to DeepTutor
Thank you for your interest in contributing to DeepTutor! We welcome developers of all skill levels to help build the next-generation intelligent learning companion.
<p align="center">
<a href="https://discord.gg/eRsjPgMU4t"><img src="https://img.shields.io/badge/Discord-Join_Community-5865F2?style=for-the-badge&logo=discord&logoColor=white" alt="Discord"></a>&nbsp;
<a href="https://github.com/HKUDS/DeepTutor/issues/78"><img src="https://img.shields.io/badge/WeChat-Join_Group-07C160?style=for-the-badge&logo=wechat&logoColor=white" alt="WeChat"></a>&nbsp;
<a href="./Communication.md"><img src="https://img.shields.io/badge/Feishu-Join_Group-00D4AA?style=for-the-badge&logo=feishu&logoColor=white" alt="Feishu"></a>
</p>
---
## Table of Contents
- [Maintainers](#maintainers)
- [Branching Strategy](#branching-strategy)
- [Quick Start for Contributors](#quick-start-for-contributors)
- [Development Setup](#development-setup)
- [Code Quality & Security](#code-quality--security)
- [Coding Standards](#coding-standards)
- [Commit Message Format](#commit-message-format)
- [Security Best Practices](#security-best-practices)
---
## Maintainer
[@pancacake](https://github.com/pancacake) — Currently just me!
---
## Branching Strategy
We use a multi-branch model to keep development organized:
| Branch | Purpose | Stability |
|---|---|---|
| `dev` | General development | May have bugs or breaking changes |
| `multi-user` | Multi-user scenario development | Experimental, focused on multi-tenant features |
> [!IMPORTANT]
> Please do **not** submit PRs directly to `main`. All contributions should target `dev` or `multi-user`.
### Which Branch Should I Target?
**Target `dev`** if your PR includes:
- New features or functionality
- Refactoring that may affect existing behavior
- Changes to APIs or configuration
- General bug fixes
**Target `multi-user`** if your PR includes:
- Multi-user / multi-tenant related features
- Session isolation, user management, or permission changes
- Collaborative or shared workspace functionality
> [!NOTE]
> When in doubt, target `dev` — it is the default development branch.
---
## Quick Start for Contributors
1. **Fork & Clone** the repository.
2. **Sync** with the target branch before starting:
```bash
git checkout dev && git pull origin dev
```
3. **Create** your feature branch from the target branch:
```bash
git checkout -b feature/your-feature-name
```
4. **Develop** your changes, following the coding standards below.
5. **Validate** by running pre-commit checks:
```bash
pre-commit run --all-files
```
6. **Submit** your Pull Request to the correct target branch (not `main` unless it's a hotfix or docs-only change).
> [!TIP]
> Browse our [Issues](https://github.com/HKUDS/DeepTutor/issues) for tasks labeled `good first issue` to find a great starting point. Comment on the issue to let others know you're working on it.
---
## Development Setup
<details>
<summary><b>Setting Up Your Environment</b></summary>
**Step 1: Create a virtual environment**
```bash
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
```
**Step 2: Install dependencies**
```bash
pip install -e ".[all]"
```
</details>
<details>
<summary><b>Setting Up Pre-commit (First Time Only)</b></summary>
**Step 1: Install pre-commit**
```bash
pip install pre-commit
# Or: conda install -c conda-forge pre-commit
```
**Step 2: Install Git hooks**
```bash
pre-commit install
```
**Step 3: Initialize the Secrets Baseline**
If you encounter false-positive secrets (like API hash placeholders), update the baseline:
```bash
detect-secrets scan > .secrets.baseline
```
</details>
### Common Commands
| Task | Command |
|---|---|
| Check all files | `pre-commit run --all-files` |
| Check quietly | `pre-commit run --all-files -q` |
| Update tools | `pre-commit autoupdate` |
| Emergency skip | `git commit --no-verify -m "message"` *(not recommended)* |
---
## Code Quality & Security
We use automated tools (configured via `pyproject.toml` and `.pre-commit-config.yaml`) to maintain high standards:
| Tool | Purpose |
|---|---|
| **Ruff** | Python linting and formatting |
| **Prettier** | Frontend & config file formatting |
| **detect-secrets** | Hardcoded secret scanning |
| **pip-audit** | Dependency vulnerability scanning |
| **Bandit** | Security issue analysis |
| **MyPy** | Static type checking |
| **Interrogate** | Docstring coverage reporting |
> [!IMPORTANT]
> Local pre-commit hooks may only show warnings, but **CI will perform strict checks** and automatically reject PRs that fail.
---
## Coding Standards
### Python
- Use **type hints** for all function signatures.
- Prefer **f-strings** for string formatting.
- Follow **PEP 8** (enforced by Ruff).
- Keep functions **small and focused** on a single responsibility.
### Documentation
- Every new module, class, and public function should have a **docstring** (Google Python Style Guide format).
- Update `README.md` if your change introduces new features or configuration.
---
## Commit Message Format
```
<type>: <short description>
[optional body]
```
| Type | Description |
|---|---|
| `feat` | A new feature (MINOR version bump) |
| `fix` | A bug fix (PATCH version bump) |
| `docs` | Documentation only changes |
| `style` | Formatting, no logic changes |
| `refactor` | Code restructuring, no new features or fixes |
| `test` | Adding or correcting tests |
| `chore` | Build process, tooling, or dependency updates |
---
## Security Best Practices
### File Uploads
- **Size Limits**: General files capped at 100 MB; PDFs capped at 50 MB.
- **Validation**: Multi-layer validation (extension + MIME type + content sanitization).
- **Sanitization**: All filenames are sanitized to prevent path traversal.
### Development Standards
- **Subprocesses**: Always use `shell=False` to prevent command injection.
- **Pathing**: Use `pathlib.Path` for cross-platform compatibility.
- **Line Endings**: LF (Unix) line endings enforced for critical scripts via `.gitattributes`.
---
Questions? Reach out on [Discord](https://discord.gg/eRsjPgMU4t). Let's build the future of AI tutoring together!
+5
View File
@@ -0,0 +1,5 @@
We provide QR codes for joining the HKUDS discussion groups on WeChat and Feishu.
You can join by scanning the QR codes below:
<img src="https://github.com/HKUDS/.github/blob/main/profile/QR.png" alt="WeChat QR Code" width="400"/>
+484
View File
@@ -0,0 +1,484 @@
# ============================================
# DeepTutor Multi-Stage Dockerfile
# ============================================
# This Dockerfile builds a production-ready image for DeepTutor
# containing both the FastAPI backend and Next.js frontend
#
# Build/run:
# docker build -t deeptutor:local .
# docker run -p 127.0.0.1:3782:3782 -p 127.0.0.1:8001:8001 \
# -v deeptutor-data:/app/data deeptutor:local
#
# Prerequisites:
# 1. Runtime settings are created under data/user/settings on first start
# 2. Configure provider profiles from the web Settings page or model_catalog.json
# ============================================
# ============================================
# Stage 1: Frontend Builder
# ============================================
# Run on the build platform natively (not under QEMU emulation).
# The output is platform-independent static assets (JS/HTML/CSS),
# so there is no need to cross-compile this stage.
FROM --platform=$BUILDPLATFORM node:22-slim AS frontend-builder
WORKDIR /app/web
# Copy package files first for better caching
COPY web/package.json web/package-lock.json* ./
# Install dependencies with generous timeout for CI environments
RUN npm config set fetch-timeout 600000 && \
npm config set fetch-retries 5 && \
npm ci --legacy-peer-deps
# Copy frontend source code
COPY web/ ./
# Provide the single source of truth for the app version so next.config.js
# can read it during ``npm run build`` and inline it into the bundle.
COPY deeptutor/__version__.py /app/deeptutor/__version__.py
# Create .env.local with the single env var the build needs (the app version,
# exposed to the browser via next.config.js). URL knowledge is no longer baked
# into the bundle: `apiUrl`/`wsUrl` in web/lib/api.ts are pass-throughs and
# the actual backend host is read at request time by web/proxy.ts from
# DEEPTUTOR_API_BASE_URL (exported by the entrypoint on every start).
RUN printf 'NEXT_PUBLIC_APP_VERSION=\n' > .env.local
# Build Next.js for production with standalone output
# This allows runtime environment variable injection
RUN npm run build
# ============================================
# Stage 1b: Node Runtime for Target Platform
# ============================================
# Provides the correctly-architected node binary for the final image.
# Unlike frontend-builder (pinned to BUILDPLATFORM), this stage pulls
# the node image matching each target platform (amd64 / arm64).
FROM node:22-slim AS node-runtime
# ============================================
# Stage 2: Python Base with Dependencies
# ============================================
FROM python:3.11-slim AS python-base
# Set environment variables
ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1 \
PYTHONIOENCODING=utf-8 \
PIP_NO_CACHE_DIR=1 \
PIP_DISABLE_PIP_VERSION_CHECK=1
WORKDIR /app
# Install system dependencies
# Note: libgl1 and libglib2.0-0 are required for OpenCV (used by mineru)
# Rust is required for building tiktoken and other packages without pre-built wheels
RUN apt-get update && apt-get install -y --no-install-recommends \
curl \
git \
build-essential \
libgl1 \
libglib2.0-0 \
libsm6 \
libxext6 \
libxrender1 \
pkg-config \
libssl-dev \
&& rm -rf /var/lib/apt/lists/* \
&& curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y
# Add Rust to PATH
ENV PATH="/root/.cargo/bin:${PATH}"
# Copy requirements and install Python dependencies
COPY requirements/ ./requirements/
COPY requirements.txt ./
RUN pip install --upgrade pip && \
pip install -r requirements.txt
# ============================================
# Stage 3: Production Image
# ============================================
FROM python:3.11-slim AS production
# Labels
LABEL maintainer="DeepTutor Team" \
description="DeepTutor: AI-Powered Personalized Learning Assistant"
# Set environment variables
ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1 \
PYTHONIOENCODING=utf-8 \
NODE_ENV=production \
DEEPTUTOR_IGNORE_PROCESS_ENV_OVERRIDES=1
# Code-execution sandbox: the restricted-subprocess backend (which the office
# skills — docx/pdf/pptx/xlsx — rely on for `exec` / `code_execution`) is
# enabled by default via the `sandbox_allow_subprocess` runtime setting
# (system.json, default on), exported to DEEPTUTOR_SANDBOX_ALLOW_SUBPROCESS at
# startup. No hardcoded ENV here — that would override the setting and block
# disabling it. docker-compose still routes exec to the hardened runner sidecar
# (DEEPTUTOR_SANDBOX_RUNNER_URL), which build_backend() prefers.
WORKDIR /app
# Install system dependencies
# Note: libgl1 and libglib2.0-0 are required for OpenCV (used by mineru)
RUN apt-get update && apt-get install -y --no-install-recommends \
curl \
ca-certificates \
bash \
supervisor \
libgl1 \
libglib2.0-0 \
libsm6 \
libxext6 \
libxrender1 \
&& rm -rf /var/lib/apt/lists/*
# Copy Node.js from node-runtime stage (platform-matched binary)
COPY --from=node-runtime /usr/local/bin/node /usr/local/bin/node
COPY --from=node-runtime /usr/local/lib/node_modules /usr/local/lib/node_modules
RUN ln -sf /usr/local/lib/node_modules/npm/bin/npm-cli.js /usr/local/bin/npm \
&& ln -sf /usr/local/lib/node_modules/npm/bin/npx-cli.js /usr/local/bin/npx \
&& node --version && npm --version
# Copy Python packages from builder stage
COPY --from=python-base /usr/local/lib/python3.11/site-packages /usr/local/lib/python3.11/site-packages
COPY --from=python-base /usr/local/bin /usr/local/bin
# Copy built frontend from frontend-builder stage (standalone mode)
# The standalone output contains a self-contained server.js + minimal node_modules
# Static assets and public/ must be copied alongside standalone manually
COPY --from=frontend-builder /app/web/.next/standalone/ ./web/
COPY --from=frontend-builder /app/web/.next/static/ ./web/.next/static/
COPY --from=frontend-builder /app/web/public/ ./web/public/
# Copy application source code
COPY deeptutor/ ./deeptutor/
COPY deeptutor_cli/ ./deeptutor_cli/
COPY scripts/ ./scripts/
COPY pyproject.toml ./
COPY requirements/ ./requirements/
COPY requirements.txt ./
# Create necessary directories (these will be overwritten by volume mounts)
RUN mkdir -p \
data/user/settings \
data/memory \
data/user/workspace/memory \
data/user/workspace/notebook \
data/user/workspace/co-writer/audio \
data/user/workspace/co-writer/tool_calls \
data/user/workspace/chat/chat \
data/user/workspace/chat/deep_solve \
data/user/workspace/chat/deep_question \
data/user/workspace/chat/deep_research/reports \
data/user/workspace/chat/math_animator \
data/user/workspace/chat/_detached_code_execution \
data/user/logs \
data/knowledge_bases
# Bake a non-root user (UID 1000) for the supervisord programs. supervisord
# itself runs as PID 1's UID — root under rootful Docker/Podman, or UID 1000
# under rootless podman + `userns_mode: keep-id` (where PID 1 is the host
# user). Each child (backend/frontend) is dropped to this `deeptutor` user via
# the per-program `user=deeptutor` directive, so the app processes stay
# non-root in either runtime. UID 1000 also matches the host user under
# keep-id with a bind mount on ./data.
RUN groupadd --system --gid 1000 deeptutor \
&& useradd --system --uid 1000 --gid 1000 --no-create-home --shell /usr/sbin/nologin deeptutor \
&& chown -R deeptutor:deeptutor /app/data /app/web/.next
# supervisord config is split into two files so the production and development
# images share one daemon-level [supervisord] section instead of duplicating it:
# - /etc/supervisor/supervisord.conf — daemon-level settings (shared)
# - /etc/supervisor/conf.d/programs.conf — the backend/frontend programs
# Production defines the programs here; the development stage overrides only
# programs.conf, leaving the shared daemon section untouched.
# Program output goes to the container's stdout/stderr so `docker logs` captures it.
RUN mkdir -p /etc/supervisor/conf.d
# Daemon-level config. No `user=` in [supervisord]: supervisord runs as PID 1's
# UID (root under rootful; UID 1000 under rootless podman + keep-id, which has
# no CAP_SETUID and would make a `user=` line fail at startup with
# "Can't drop privilege as nonroot user" — see supervisord options.py). The
# pidfile lives in /tmp, which is world-writable, so supervisord can create it
# whether it runs as root or UID 1000; /var/run is root-owned and not writable
# by UID 1000 under rootless keep-id.
RUN cat > /etc/supervisor/supervisord.conf <<'EOF'
[supervisord]
nodaemon=true
logfile=/dev/null
logfile_maxbytes=0
pidfile=/tmp/supervisord.pid
[include]
files = /etc/supervisor/conf.d/programs.conf
EOF
RUN sed -i 's/\r$//' /etc/supervisor/supervisord.conf
# Program definitions (production). Each child drops to the unprivileged
# deeptutor user (UID 1000) via per-program `user=deeptutor`; see the note on
# the user= design above the daemon config.
RUN cat > /etc/supervisor/conf.d/programs.conf <<'EOF'
[program:backend]
command=/bin/bash /app/start-backend.sh
directory=/app
user=deeptutor
autostart=true
autorestart=true
stdout_logfile=/dev/fd/1
stdout_logfile_maxbytes=0
stderr_logfile=/dev/fd/2
stderr_logfile_maxbytes=0
environment=PYTHONPATH="/app",PYTHONUNBUFFERED="1"
[program:frontend]
command=/bin/bash /app/start-frontend.sh
directory=/app/web
user=deeptutor
autostart=true
autorestart=true
startsecs=5
stdout_logfile=/dev/fd/1
stdout_logfile_maxbytes=0
stderr_logfile=/dev/fd/2
stderr_logfile_maxbytes=0
environment=NODE_ENV="production"
EOF
RUN sed -i 's/\r$//' /etc/supervisor/conf.d/programs.conf
# Create backend startup script
RUN cat > /app/start-backend.sh <<'EOF'
#!/bin/bash
set -e
BACKEND_PORT=${BACKEND_PORT:-8001}
BACKEND_HOST=${BACKEND_HOST:-0.0.0.0}
echo "[Backend] 🚀 Starting FastAPI backend on ${BACKEND_HOST}:${BACKEND_PORT}..."
# Run uvicorn directly - the application's logging system already handles:
# 1. Console output (visible in docker logs)
# 2. File logging to data/user/logs/ai_tutor_*.log
#
# BACKEND_HOST defaults to 0.0.0.0 (LAN-reachable, matches bridge-mode
# port publishing). Set BACKEND_HOST=127.0.0.1 when running with
# network_mode: host to keep the backend on loopback only.
exec python -m uvicorn deeptutor.api.main:app --host ${BACKEND_HOST} --port ${BACKEND_PORT} --no-access-log
EOF
RUN sed -i 's/\r$//' /app/start-backend.sh && chmod +x /app/start-backend.sh
# Create frontend startup script
# This script starts the Next.js standalone server. URL knowledge is no
# longer baked into the bundle: web/proxy.ts rewrites /api/* and /ws/* to
# the configured backend at request time, reading DEEPTUTOR_API_BASE_URL
# (exported by the entrypoint from data/user/settings/system.json).
RUN cat > /app/start-frontend.sh <<'EOF'
#!/bin/bash
set -e
FRONTEND_PORT=${FRONTEND_PORT:-3782}
FRONTEND_HOST=${FRONTEND_HOST:-0.0.0.0}
echo "[Frontend] 🚀 Starting Next.js frontend on ${FRONTEND_HOST}:${FRONTEND_PORT}..."
export PORT=${FRONTEND_PORT}
export HOSTNAME=${FRONTEND_HOST}
exec node /app/web/server.js
EOF
RUN sed -i 's/\r$//' /app/start-frontend.sh && chmod +x /app/start-frontend.sh
# Create entrypoint script
RUN cat > /app/entrypoint.sh <<'EOF'
#!/bin/bash
set -e
echo "============================================"
echo "🚀 Starting DeepTutor"
echo "============================================"
export DEEPTUTOR_IGNORE_PROCESS_ENV_OVERRIDES=1
# Docker is JSON-driven. Ignore runtime env names even if the host or a stale
# Compose environment provides them; the entrypoint re-exports values from
# data/user/settings/*.json below.
for key in \
BACKEND_PORT \
FRONTEND_PORT \
NEXT_PUBLIC_API_BASE_EXTERNAL \
NEXT_PUBLIC_API_BASE \
CORS_ORIGIN \
CORS_ORIGINS \
DISABLE_SSL_VERIFY \
CHAT_ATTACHMENT_DIR \
AUTH_ENABLED \
NEXT_PUBLIC_AUTH_ENABLED \
AUTH_USERNAME \
AUTH_PASSWORD_HASH \
AUTH_TOKEN_EXPIRE_HOURS \
AUTH_COOKIE_SECURE \
POCKETBASE_URL \
POCKETBASE_PORT \
POCKETBASE_EXTERNAL_URL \
POCKETBASE_ADMIN_EMAIL \
POCKETBASE_ADMIN_PASSWORD \
DEEPTUTOR_API_BASE_URL \
DEEPTUTOR_AUTH_ENABLED; do
unset "$key"
done
# Initialize user data directories if empty
echo "📁 Checking data directories..."
echo " Ensuring runtime settings and workspace layout..."
python -c "
from pathlib import Path
from deeptutor.services.setup import init_user_directories
init_user_directories(Path('/app'))
" 2>/dev/null || echo " ⚠️ Directory initialization skipped (will be created on first use)"
# Idempotent: re-chown /app/data so the unprivileged `deeptutor` user (UID 1000)
# owns it. Cheap on no-op; the only first-start cost is one stat per file.
chown -R deeptutor:deeptutor /app/data 2>/dev/null || true
echo "⚙️ Loading runtime JSON settings..."
eval "$(python - <<'PY'
import shlex
from deeptutor.services.config import export_runtime_settings_to_env
for key, value in export_runtime_settings_to_env(overwrite=True).items():
print(f"export {key}={shlex.quote(str(value))}")
PY
)"
export BACKEND_PORT=${BACKEND_PORT:-8001}
export FRONTEND_PORT=${FRONTEND_PORT:-3782}
# DEEPTUTOR_API_BASE_URL and DEEPTUTOR_AUTH_ENABLED are exported by the
# export_runtime_settings_to_env eval above (see render_environment in
# deeptutor/services/config/runtime_settings.py). web/proxy.ts reads them at
# request time to rewrite /api/* and /ws/* to the backend and to gate the login
# redirect. Keeping them in the single JSON-backed exporter means the Docker and
# `deeptutor start` paths stay in sync.
echo "📌 API Base URL (proxy): ${DEEPTUTOR_API_BASE_URL:-http://localhost:${BACKEND_PORT}}"
echo "📌 Auth enabled: ${DEEPTUTOR_AUTH_ENABLED:-false}"
echo "📌 Backend Port: ${BACKEND_PORT}"
echo "📌 Frontend Port: ${FRONTEND_PORT}"
echo "============================================"
echo "📦 Configuration loaded from:"
echo " - data/user/settings/system.json"
echo " - data/user/settings/auth.json"
echo " - data/user/settings/integrations.json"
echo " - data/user/settings/model_catalog.json"
echo " - data/user/settings/main.yaml"
echo " - data/user/settings/agents.yaml"
echo "============================================"
# Hand off to supervisord as PID 1. The daemon-level config deliberately omits
# `user=` so supervisord inherits PID 1's UID and stays portable across rootful
# and rootless-keep-id runtimes; children drop to the deeptutor user via
# per-program `user=`. Full rationale lives next to the [supervisord] section
# in the build step that writes /etc/supervisor/supervisord.conf.
exec /usr/bin/supervisord -c /etc/supervisor/supervisord.conf
EOF
RUN sed -i 's/\r$//' /app/entrypoint.sh && chmod +x /app/entrypoint.sh
RUN cat > /app/healthcheck.py <<'EOF'
from pathlib import Path
import json
import urllib.request
port = 8001
settings_path = Path("/app/data/user/settings/system.json")
try:
settings = json.loads(settings_path.read_text(encoding="utf-8"))
port = int(settings.get("backend_port") or port)
except Exception:
pass
urllib.request.urlopen(f"http://localhost:{port}/", timeout=5).close()
EOF
# Expose ports
EXPOSE 8001 3782
# Health check. Read the port from JSON so standalone `docker run` does not
# depend on a Dockerfile-level BACKEND_PORT default.
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
CMD python /app/healthcheck.py
# Set entrypoint
ENTRYPOINT ["/app/entrypoint.sh"]
# ============================================
# Stage 4: Development Image (Optional)
# ============================================
FROM production AS development
# Re-add full node_modules for development hot-reload
# (Production uses standalone output which doesn't include full node_modules)
COPY --from=frontend-builder /app/web/node_modules ./web/node_modules
COPY --from=frontend-builder /app/web/package.json ./web/package.json
COPY --from=frontend-builder /app/web/next.config.js ./web/next.config.js
# `next dev` runs as the unprivileged deeptutor user (via `user=deeptutor` in
# the supervisord config) and must create/write its build cache under
# /app/web/.next, so give that user ownership of the web dir and the cache.
RUN mkdir -p /app/web/.next \
&& chown deeptutor:deeptutor /app/web /app/web/.next
# Install development tools
RUN apt-get update && apt-get install -y --no-install-recommends \
vim \
git \
&& rm -rf /var/lib/apt/lists/*
# Install development Python packages
RUN pip install --no-cache-dir \
pre-commit \
black \
ruff
# Development overrides only the program definitions (uvicorn --reload and
# `next dev`); the shared daemon-level /etc/supervisor/supervisord.conf from
# the production stage is reused as-is.
RUN cat > /etc/supervisor/conf.d/programs.conf <<'EOF'
[program:backend]
command=python -m uvicorn deeptutor.api.main:app --host 0.0.0.0 --port %(ENV_BACKEND_PORT)s --reload --no-access-log
directory=/app
user=deeptutor
autostart=true
autorestart=true
stdout_logfile=/dev/fd/1
stdout_logfile_maxbytes=0
stderr_logfile=/dev/fd/2
stderr_logfile_maxbytes=0
environment=PYTHONPATH="/app",PYTHONUNBUFFERED="1"
[program:frontend]
command=/bin/bash -c "cd /app/web && node node_modules/next/dist/bin/next dev -H 0.0.0.0 -p ${FRONTEND_PORT:-3782}"
directory=/app/web
user=deeptutor
autostart=true
autorestart=true
startsecs=5
stdout_logfile=/dev/fd/1
stdout_logfile_maxbytes=0
stderr_logfile=/dev/fd/2
stderr_logfile_maxbytes=0
environment=NODE_ENV="development"
EOF
RUN sed -i 's/\r$//' /etc/supervisor/conf.d/programs.conf
# Development ports
EXPOSE 8001 3782
+102
View File
@@ -0,0 +1,102 @@
# ============================================
# DeepTutor Sandbox Runner Sidecar Image
# ============================================
# A deliberately small, least-privileged image whose *only* job is to execute
# untrusted shell commands on behalf of the main app, isolated in its own
# container. The main app talks to it over HTTP via RunnerSidecarBackend
# (see deeptutor/services/sandbox/backends.py), pointed here through
# DEEPTUTOR_SANDBOX_RUNNER_URL.
#
# Build/run (normally orchestrated by docker-compose, not by hand):
# docker build -f Dockerfile.runner -t deeptutor-sandbox-runner:local .
# docker run --rm -p 8900:8900 deeptutor-sandbox-runner:local
#
# Why no app code beyond server.py: the runner ships ONLY the stdlib HTTP server
# plus a set of common CLI tools. It must not depend on the DeepTutor package or
# any heavy framework — keeping the attack surface and image size minimal.
# ============================================
FROM python:3.11-slim
# ----- Common CLI + data tooling -------------------------------------------
# A pragmatic toolbelt for the kinds of shell tasks the model runs (clone a
# repo, fetch a URL, grep code, slice JSON). numpy/pandas are installed via pip
# so simple data crunching works out of the box. Trim this list if image size
# matters more than coverage for your deployment.
RUN apt-get update && apt-get install -y --no-install-recommends \
git \
curl \
ca-certificates \
ripgrep \
jq \
build-essential \
fonts-wqy-zenhei \
&& rm -rf /var/lib/apt/lists/*
# fonts-wqy-zenhei: a CJK font so reportlab-generated PDFs render Chinese/JP/KR
# instead of tofu boxes (the pdf SKILL.md registers it from
# /usr/share/fonts/truetype/wqy/wqy-zenhei.ttc). It MUST be a TrueType font:
# reportlab cannot embed CFF/OpenType outlines, so fonts-noto-cjk (CFF .otf)
# would fail to register. python:3.11-slim ships no CJK fonts on its own.
# build-essential ships gcc / g++ / make + libc headers so the `code_execution`
# tool can compile and run C (`cc`) and C++ (`c++ -std=c++17`) snippets, not
# just Python. Drop it if your deployment only needs Python execution.
# Python data + office-document stack. Kept separate so it is easy to drop.
# --no-cache-dir keeps the layer lean.
#
# numpy/pandas cover simple data crunching. The rest back the built-in office
# skills (deeptutor/skills/builtin/{docx,pptx,xlsx,pdf}/SKILL.md): the model
# writes short Python against these libs and runs it via the `exec` tool, so
# they MUST be present here in the sidecar — the runner image carries no
# deeptutor deps of its own. All ship as wheels (no extra apt needed). Keep this
# list in sync with the libraries those SKILL.md playbooks promise are available.
RUN pip install --no-cache-dir \
numpy \
pandas \
python-docx \
python-pptx \
openpyxl \
pypdf \
pdfplumber \
PyMuPDF \
reportlab \
lxml \
defusedxml \
Pillow
# Optional, NOT installed by default: LibreOffice (`soffice`) for format
# conversion (.doc→.docx, →PDF) and Excel formula recalculation. It is large
# (~400MB+), so the office skills gate every use on `command -v soffice` and
# degrade gracefully when absent. To enable it for your deployment, uncomment:
# RUN apt-get update && apt-get install -y --no-install-recommends \
# libreoffice-writer libreoffice-calc libreoffice-impress \
# && rm -rf /var/lib/apt/lists/*
# ----- Non-root user --------------------------------------------------------
# Commands run as an unprivileged user (uid 1000) so a sandbox escape cannot act
# as root inside the container. uid 1000 matches the host user that owns the
# shared task-workspace volume in the common single-user deployment, so files
# written into ./data/user stay readable by the main app.
RUN useradd --create-home --uid 1000 --shell /bin/bash runner
WORKDIR /app
# Ship just the server module. We copy it to a flat path and run it directly
# (python /app/server.py) rather than `python -m deeptutor...`: the runner image
# intentionally does NOT contain the deeptutor package, so the module path would
# not resolve. Direct-file execution is the simple, dependency-free choice.
COPY deeptutor/services/sandbox/runner/server.py /app/server.py
# The workspace shared with the main app is mounted here at runtime by
# docker-compose (./data/user:/app/data/user), at the *same* path in both
# containers so the mount contract (host_path == sandbox_path) holds.
ENV RUNNER_PORT=8900 \
PYTHONUNBUFFERED=1
EXPOSE 8900
USER runner
CMD ["python", "/app/server.py"]
+202
View File
@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to the Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by the Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding any notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. Please also get an
"Alarm or alarm" copyright header and make that the reference
to the Apache License and the Disclaimer of Warranty (Alarm is
the umbrella trademark for a collection of Open Source projects).
Copyright 2025 Data Intelligence Lab, The University of Hong Kong
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+2
View File
@@ -0,0 +1,2 @@
recursive-include deeptutor_web *
recursive-include deeptutor_web/.next *
+842
View File
@@ -0,0 +1,842 @@
<div align="center">
<p align="center"><img src="assets/figs/logo/logo.png" alt="DeepTutor logo" height="56" style="vertical-align: middle;">&nbsp;<img src="assets/figs/logo/banner.png" alt="DeepTutor" height="48" style="vertical-align: middle;"></p>
# DeepTutor: Lifelong Personalized Tutoring
<p align="center">
<a href="https://deeptutor.info" target="_blank"><img alt="Docs — deeptutor.info" src="https://img.shields.io/badge/Docs-deeptutor.info%20%E2%86%97-0A0A0A?style=for-the-badge&labelColor=F5F5F4" height="36"></a>
</p>
<p align="center">
<a href="https://trendshift.io/repositories/17099?utm_source=repository-badge&amp;utm_medium=badge&amp;utm_campaign=badge-repository-17099" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/repositories/17099" alt="HKUDS%2FDeepTutor | Trendshift" width="250" height="55"/></a>&nbsp;
<a href="https://trendshift.io/repositories/17099?utm_source=trendshift-badge&amp;utm_medium=badge&amp;utm_campaign=badge-trendshift-17099" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/17099/daily" alt="HKUDS%2FDeepTutor | Trendshift" width="250" height="55"/></a>&nbsp;
<a href="https://trendshift.io/repositories/17099?utm_source=trendshift-badge&amp;utm_medium=badge&amp;utm_campaign=badge-trendshift-17099" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/17099/weekly?language=Python" alt="HKUDS%2FDeepTutor | Trendshift" width="250" height="55"/></a>
</p>
<p align="center">
<a href="README.md"><img alt="English" height="40" src="https://img.shields.io/badge/English-BCDCF7"></a>&nbsp;
<a href="assets/README/README_CN.md"><img alt="简体中文" height="40" src="https://img.shields.io/badge/简体中文-CDCFD4"></a>&nbsp;
<a href="assets/README/README_JA.md"><img alt="日本語" height="40" src="https://img.shields.io/badge/日本語-CDCFD4"></a>&nbsp;
<a href="assets/README/README_ES.md"><img alt="Español" height="40" src="https://img.shields.io/badge/Español-CDCFD4"></a>&nbsp;
<a href="assets/README/README_FR.md"><img alt="Français" height="40" src="https://img.shields.io/badge/Français-CDCFD4"></a>&nbsp;
<a href="assets/README/README_AR.md"><img alt="Arabic" height="40" src="https://img.shields.io/badge/Arabic-CDCFD4"></a>&nbsp;
<a href="assets/README/README_RU.md"><img alt="Русский" height="40" src="https://img.shields.io/badge/Русский-CDCFD4"></a>&nbsp;
<a href="assets/README/README_HI.md"><img alt="Hindi" height="40" src="https://img.shields.io/badge/Hindi-CDCFD4"></a>&nbsp;
<a href="assets/README/README_PT.md"><img alt="Português" height="40" src="https://img.shields.io/badge/Português-CDCFD4"></a>&nbsp;
<a href="assets/README/README_TH.md"><img alt="Thai" height="40" src="https://img.shields.io/badge/Thai-CDCFD4"></a>&nbsp;
<a href="assets/README/README_PL.md"><img alt="Polski" height="40" src="https://img.shields.io/badge/Polski-CDCFD4"></a>
</p>
[![Python 3.11+](https://img.shields.io/badge/Python-3.11%2B-3776AB?style=flat-square&logo=python&logoColor=white)](https://www.python.org/downloads/)
[![Next.js 16](https://img.shields.io/badge/Next.js-16-000000?style=flat-square&logo=next.js&logoColor=white)](https://nextjs.org/)
[![License](https://img.shields.io/badge/License-Apache_2.0-blue?style=flat-square)](LICENSE)
[![GitHub release](https://img.shields.io/github/v/release/HKUDS/DeepTutor?style=flat-square&color=brightgreen)](https://github.com/HKUDS/DeepTutor/releases)
[![arXiv](https://img.shields.io/badge/arXiv-2604.26962-b31b1b?style=flat-square&logo=arxiv&logoColor=white)](https://arxiv.org/abs/2604.26962)
[![Discord](https://img.shields.io/badge/Discord-Community-5865F2?style=flat-square&logo=discord&logoColor=white)](https://discord.gg/eRsjPgMU4t)
[![Feishu](https://img.shields.io/badge/Feishu-Group-00D4AA?style=flat-square&logo=feishu&logoColor=white)](./Communication.md)
[![WeChat](https://img.shields.io/badge/WeChat-Group-07C160?style=flat-square&logo=wechat&logoColor=white)](https://github.com/HKUDS/DeepTutor/issues/78)
[Features](#-key-features) · [Get Started](#-get-started) · [Explore](#-explore-deeptutor) · [CLI](#%EF%B8%8F-deeptutor-cli--agent-native-interface) · [Ecosystem](#-ecosystem--eduhub--the-skills-community) · [Community](#-community)
</div>
---
> 🤝 **We welcome any kinds of contributing!** Vote on roadmap items or propose new ones at [`Roadmap`](https://github.com/HKUDS/DeepTutor/issues/498), and see our [Contributing Guide](CONTRIBUTING.md) for branching strategy, coding standards, and how to get started.
### 📦 Releases
> **[2026.7.9]** [v1.5.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.5.1) — Remove a single failed document from a knowledge base — even one stuck in an **error** state — instead of deleting and rebuilding the whole base.
> **[2026.7.4]** [v1.5.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.5.0) — LlamaIndex ingestion now honors your **Document Parsing** engine with multimodal image extraction, Partner & Soul ids stay URL-safe for non-Latin names, and optional RAG extras install cleanly on Python 3.14+.
<details>
<summary><b>Past releases (more than 1 week ago)</b></summary>
> **[2026.6.30]** [v1.4.15](https://github.com/HKUDS/DeepTutor/releases/tag/v1.4.15) — A native **Mattermost** channel for Partners, plus fixes so Guided Learning multiple-choice questions grade correctly and a configured zero chunk overlap is honored.
> **[2026.6.29]** [v1.4.14](https://github.com/HKUDS/DeepTutor/releases/tag/v1.4.14) — Click an assigned partner to chat in one step, Deep Research flags partial reports, LightRAG indexes without MinerU, FAISS handles non-ASCII paths, and PocketBase sessions are isolated per user.
> **[2026.6.27]** [v1.4.13](https://github.com/HKUDS/DeepTutor/releases/tag/v1.4.13) — Partners support non-Latin names and become assignable to users, logos render after login (#599), tiny knowledge bases retrieve reliably, and containers start cleanly under rootless Podman.
> **[2026.6.24]** [v1.4.12](https://github.com/HKUDS/DeepTutor/releases/tag/v1.4.12) — A new **LightRAG Server** retrieval engine, a lightweight **PyMuPDF4LLM** parsing engine, and a FAISS vector backend that makes large knowledge-base retrieval dramatically faster.
> **[2026.6.23]** [v1.4.11](https://github.com/HKUDS/DeepTutor/releases/tag/v1.4.11) — Native tool calling on every cloud OpenAI-compatible provider, a redesigned admin Users page, LaTeX in quiz options, an honest session-loading spinner, and configurable container host binding.
> **[2026.6.21]** [v1.4.10](https://github.com/HKUDS/DeepTutor/releases/tag/v1.4.10) — A self-service **Profile** page with avatars, a rootless-ready container guide with a single-port request-time proxy, and deny-by-default MCP tools for non-admin users.
> **[2026.6.19]** [v1.4.9](https://github.com/HKUDS/DeepTutor/releases/tag/v1.4.9) — Settings polish: Search shows only the fields your provider needs, connection profiles can be renamed and auto-named by provider, and graded Mastery Path questions flow into your Question Bank.
> **[2026.6.18]** [v1.4.8](https://github.com/HKUDS/DeepTutor/releases/tag/v1.4.8) — Connect your own **Partners** under **My Agents** and consult them live in chat — answering through their own persona, library and skills — and each Partner gains its own private memory.
> **[2026.6.18]** [v1.4.7](https://github.com/HKUDS/DeepTutor/releases/tag/v1.4.7) — Connect your local **Claude Code / Codex** and consult it live mid-turn, **My Agents** graduates to a top-level `/agents`, and Partner conversations gain branch / resume / delete with a replayable trace.
> **[2026.6.17]** [v1.4.6](https://github.com/HKUDS/DeepTutor/releases/tag/v1.4.6) — Four-surface consolidation: a Space learning dashboard with importable **My Agents** and top-level Memory, a **Knowledge Center** with GraphRAG / PageIndex / LightRAG / linked-KB / Obsidian, opened-up Settings, and per-model capability gating.
> **[2026.6.14]** [v1.4.5](https://github.com/HKUDS/DeepTutor/releases/tag/v1.4.5) — Guided Learning rebuilt on the chat agent loop with a hard per-type mastery gate and a `/learning` dashboard, a new loop-plugin framework, plus Markdown export / save-to-notebook for Partner conversations.
> **[2026.6.13]** [v1.4.4](https://github.com/HKUDS/DeepTutor/releases/tag/v1.4.4) — Install community skills from [ClawHub](https://clawhub.ai/) with `deeptutor skill install` behind a security gate, plus real in-browser DOCX/XLSX previews for knowledge-base files.
> **[2026.6.12]** [v1.4.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.4.3) — TutorBot becomes **Partners** on a production-grade IM pipeline (15 channels, live streaming), Chat moves to a single agent loop, real per-user isolation, and a rebuilt Visualize.
> **[2026.5.28]** [v1.4.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.4.2) — Stability + polish: Gemini 2.5+ unblocked across Visualize and Chat, auth-routing fix (#485), smooth-streaming chat UX, a Recents sidebar, and Lemonade local-provider support.
> **[2026.5.27]** [v1.4.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.4.1) — Security + stability: TutorBot tool sandbox locked down, per-user resource isolation, multimodal image fallback, an HTTP/SSE API for TutorBots, and a v1.4.0 chat regression fix.
> **[2026.5.22]** [v1.4.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.4.0) — GA cut of v1.4: Auto Mode, three-layer Memory, agentic Deep Research / Solve / Question, LlamaIndex RAG refactor, Visualize/Animator merge, and restart-safe turn runtime.
> **[2026.5.21]** [v1.4.0-beta](https://github.com/HKUDS/DeepTutor/releases/tag/v1.4.0-beta) — Three-layer Memory workbench (L1/L2/L3), every chat capability rebuilt on a single agentic engine, LlamaIndex-only RAG, and a unified Settings + Capabilities surface.
> **[2026.5.10]** [v1.3.10](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.10) — Remote Docker CORS recovery, `DISABLE_SSL_VERIFY` across SDK providers, safer code-block citations, and optional Matrix E2EE add-on.
> **[2026.5.9]** [v1.3.9](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.9) — TutorBot Zulip and NVIDIA NIM support, safer thinking-model routing, `deeptutor start`, sidebar tooltips, and session-store parity.
> **[2026.5.8]** [v1.3.8](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.8) — Optional multi-user deployments with isolated user workspaces, admin grants, auth routes, and scoped runtime access.
> **[2026.5.4]** [v1.3.7](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.7) — Thinking-model/provider fixes, visible Knowledge index history, and safer Co-Writer clear/template editing.
> **[2026.5.3]** [v1.3.6](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.6) — Catalog-based model selection for chat and TutorBot, safer RAG re-indexing, OpenAI Responses token-limit fixes, and Skills editor validation.
> **[2026.5.2]** [v1.3.5](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.5) — Smoother local launch settings, safer RAG queries, cleaner local embedding auth, and Settings dark-mode polish.
> **[2026.5.1]** [v1.3.4](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.4) — Book page chat persistence and rebuild flows, chat-to-book references, stronger language/reasoning handling, RAG document extraction hardening.
> **[2026.4.30]** [v1.3.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.3) — NVIDIA NIM + Gemini embedding support, unified Space context for chat history/skills/memory, session snapshots, RAG re-index resilience.
> **[2026.4.29]** [v1.3.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.2) — Transparent embedding endpoint URLs, RAG re-index resilience for invalid persisted vectors, memory cleanup for thinking-model output, Deep Solve runtime fix.
> **[2026.4.28]** [v1.3.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.1) — Stability: safer RAG routing & embedding validation, Docker persistence, IME-safe input, Windows/GBK robustness.
> **[2026.4.27]** [v1.3.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.0) — Versioned KB indexes with re-index workflow, rebuilt Knowledge workspace, embedding auto-discovery with new adapters, Space hub.
> **[2026.4.25]** [v1.2.5](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.5) — Persistent chat attachments with file-preview drawer, attachment-aware capability pipelines, TutorBot Markdown export.
> **[2026.4.25]** [v1.2.4](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.4) — Text/code/SVG attachments, one-command Setup Tour, Markdown chat export, compact KB management UI.
> **[2026.4.24]** [v1.2.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.3) — Document attachments (PDF/DOCX/XLSX/PPTX), reasoning thinking-block display, Soul template editor, Co-Writer save-to-notebook.
> **[2026.4.22]** [v1.2.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.2) — User-authored Skills system, chat input performance overhaul, TutorBot auto-start, Book Library UI, visualization fullscreen.
> **[2026.4.21]** [v1.2.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.1) — Per-stage token limits, Regenerate response across all entry points, RAG & Gemma compatibility fixes.
> **[2026.4.20]** [v1.2.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.0) — Book Engine "living book" compiler, multi-document Co-Writer, interactive HTML visualizations, Question Bank @-mention.
> **[2026.4.18]** [v1.1.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.2) — Schema-driven Channels tab, RAG single-pipeline consolidation, externalized chat prompts.
> **[2026.4.17]** [v1.1.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.1) — Universal "Answer now", Co-Writer scroll sync, unified settings panel, streaming Stop button.
> **[2026.4.15]** [v1.1.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.0) — LaTeX block math overhaul, LLM diagnostic probe, Docker + local LLM guidance.
> **[2026.4.14]** [v1.1.0-beta](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.0-beta) — Bookmarkable sessions, Snow theme, WebSocket heartbeat & auto-reconnect, embedding registry overhaul.
> **[2026.4.13]** [v1.0.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.0.3) — Question Notebook with bookmarks & categories, Mermaid in Visualize, embedding mismatch detection, Qwen/vLLM compatibility, LM Studio & llama.cpp support, and Glass theme.
> **[2026.4.11]** [v1.0.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.0.2) — Search consolidation with SearXNG fallback, provider switch fix, and frontend resource leak fixes.
> **[2026.4.10]** [v1.0.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.0.1) — Visualize capability (Chart.js/SVG), quiz duplicate prevention, and o4-mini model support.
> **[2026.4.10]** [v1.0.0-beta.4](https://github.com/HKUDS/DeepTutor/releases/tag/v1.0.0-beta.4) — Embedding progress tracking with rate-limit retry, cross-platform dependency fixes, and MIME validation fix.
> **[2026.4.8]** [v1.0.0-beta.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.0.0-beta.3) — Native OpenAI/Anthropic SDK (drop litellm), Windows Math Animator support, robust JSON parsing, and full Chinese i18n.
> **[2026.4.7]** [v1.0.0-beta.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.0.0-beta.2) — Hot settings reload, MinerU nested output, WebSocket fix, and Python 3.11+ minimum.
> **[2026.4.4]** [v1.0.0-beta.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.0.0-beta.1) — Agent-native architecture rewrite (~200k lines): Tools + Capabilities plugin model, CLI & SDK, TutorBot, Co-Writer, Guided Learning, and persistent memory.
> **[2026.1.23]** [v0.6.0](https://github.com/HKUDS/DeepTutor/releases/tag/v0.6.0) — Session persistence, incremental document upload, flexible RAG pipeline import, and full Chinese localization.
> **[2026.1.18]** [v0.5.2](https://github.com/HKUDS/DeepTutor/releases/tag/v0.5.2) — Docling support for RAG-Anything, logging system optimization, and bug fixes.
> **[2026.1.15]** [v0.5.0](https://github.com/HKUDS/DeepTutor/releases/tag/v0.5.0) — Unified service configuration, RAG pipeline selection per knowledge base, question generation overhaul, and sidebar customization.
> **[2026.1.9]** [v0.4.0](https://github.com/HKUDS/DeepTutor/releases/tag/v0.4.0) — Multi-provider LLM & embedding support, new home page, RAG module decoupling, and environment variable refactor.
> **[2026.1.5]** [v0.3.0](https://github.com/HKUDS/DeepTutor/releases/tag/v0.3.0) — Unified PromptManager architecture, GitHub Actions CI/CD, and pre-built Docker images on GHCR.
> **[2026.1.2]** [v0.2.0](https://github.com/HKUDS/DeepTutor/releases/tag/v0.2.0) — Docker deployment, Next.js 16 & React 19 upgrade, WebSocket security hardening, and critical vulnerability fixes.
</details>
### 📰 News
- **2026-05-22** 🌐 Official docs site live at [**deeptutor.info**](https://deeptutor.info/) — guides, references, and capability tours in one place.
- **2026-04-19** 🎉 20k stars in 111 days! Thank you for the support toward truly personalized, intelligent tutoring.
- **2026-04-10** 📄 Our paper is live on arXiv — read the [preprint](https://arxiv.org/abs/2604.26962) for the design and ideas behind DeepTutor.
- **2026-02-06** 🚀 10k stars in just 39 days! A huge thank you to our incredible community.
- **2026-01-01** 🎊 Happy New Year! Join our [Discord](https://discord.gg/eRsjPgMU4t), [WeChat](https://github.com/HKUDS/DeepTutor/issues/78), or [Discussions](https://github.com/HKUDS/DeepTutor/discussions) — let's shape DeepTutor together.
- **2025-12-29** 🎓 DeepTutor is officially released!
## ✨ Key Features
DeepTutor is an agent-native learning workspace that connects tutoring, problem solving, quiz generation, research, visualization, and mastery practice in one extensible system.
- **One runtime for every mode** — Chat, Quiz, Research, Visualize, Solve, and Mastery Path run on the same agent loop, so you switch the objective, not the engine, and context moves with the learner.
- **Connected learning context** — Knowledge bases, books, Co-Writer drafts, notebooks, question banks, personas, and Memory stay available across every workflow instead of living in isolated tools.
- **Subagents and Partners** — consult a live Claude Code, Codex, or Partner from any turn (or import their past conversations), and run persistent IM companions on the same brain.
- **Multi-engine knowledge** — versioned RAG libraries across LlamaIndex, PageIndex, GraphRAG, LightRAG, or a linked Obsidian vault, with pluggable document parsing.
- **Extensible tools and skills** — built-in tools, MCP servers, image / video / voice generation models, and installable community skills from EduHub.
- **Inspectable memory** — L1 traces, L2 surface summaries, and L3 synthesis make personalization visible and editable, with a Memory Graph that traces every claim back to its evidence.
---
## 🚀 Get Started
DeepTutor ships four installation paths. They all share one workspace layout: settings live in `data/user/settings/` under the directory you launch from (or under `DEEPTUTOR_HOME` / `deeptutor start --home` if you set one explicitly). For the full app, the recommended flow is **pick a workspace directory → install → `deeptutor init` → `deeptutor start`**.
<details>
<summary><b>Option 1 — Install From PyPI</b> · full local Web app + CLI, no clone required</summary>
Full local Web app + CLI, no clone required. Needs **Python 3.11+** and a **Node.js 20+** runtime on PATH (the packaged Next.js standalone server is spawned by `deeptutor start`).
```bash
mkdir -p my-deeptutor && cd my-deeptutor
pip install -U deeptutor
deeptutor init # prompts for ports + LLM provider + optional embedding
deeptutor start # starts backend + frontend; keep the terminal open
```
`deeptutor init` prompts for backend port (default `8001`), frontend port (default `3782`), LLM provider / base URL / API key / model, and an optional embedding provider for Knowledge Base / RAG.
After `deeptutor start`, open the frontend URL printed in the terminal — by default [http://127.0.0.1:3782](http://127.0.0.1:3782). Press `Ctrl+C` in that terminal to stop both backend and frontend. Skipping `deeptutor init` is fine for a quick trial; the app boots with default ports and empty model settings, configure them later in **Settings → Models**.
</details>
<details>
<summary><b>Option 2 — Install From Source</b> · develop against a checkout</summary>
For development against a checkout. Use **Python 3.11+** and **Node.js 22 LTS** to match CI and Docker.
```bash
git clone https://github.com/HKUDS/DeepTutor.git
cd DeepTutor
# Create a venv (macOS/Linux). Windows PowerShell:
# py -3.11 -m venv .venv ; .\.venv\Scripts\Activate.ps1
python3 -m venv .venv && source .venv/bin/activate
python -m pip install --upgrade pip
# Install backend + frontend deps
python -m pip install -e .
( cd web && npm ci --legacy-peer-deps )
deeptutor init
deeptutor start
```
Source installs run Next.js in dev mode against the local `web/` directory; everything else (config layout, ports, stop with `Ctrl+C`) matches Option 1.
<details>
<summary><b>Conda environment</b> (instead of <code>venv</code>)</summary>
```bash
conda create -n deeptutor python=3.11
conda activate deeptutor
python -m pip install --upgrade pip
```
</details>
<details>
<summary><b>Optional install extras</b> — dev / partners / matrix / math-animator</summary>
```bash
pip install -e ".[dev]" # tests/lint tools
pip install -e ".[partners]" # Partner IM channel SDKs + MCP client
pip install -e ".[matrix]" # Matrix channel without E2EE/libolm
pip install -e ".[matrix-e2e]" # Matrix E2EE; requires libolm
pip install -e ".[math-animator]" # Manim addon; requires LaTeX/ffmpeg/system libs
```
</details>
<details>
<summary><b>Frontend dependency tweaks & dev-server troubleshooting</b></summary>
**Changing frontend dependencies:** run `npm install --legacy-peer-deps` to refresh `web/package-lock.json`, then commit both `web/package.json` and `web/package-lock.json`.
**Stuck dev server:** if `deeptutor start` reports an existing frontend that isn't responding, stop the PID it prints. If no Next.js process is actually running, the lock files are stale — remove them and retry:
```bash
rm -f web/.next/dev/lock web/.next/lock
deeptutor start
```
</details>
</details>
<details>
<summary><b>Option 3 — Docker</b> · one self-contained container</summary>
One container for the full Web app. Images on GitHub Container Registry:
- `ghcr.io/hkuds/deeptutor:latest` — stable release
- `ghcr.io/hkuds/deeptutor:pre` — pre-release, when available
> See [CONTAINERIZATION.md](./CONTAINERIZATION.md) for podman/rootless/read-only-rootfs deployments and the full per-installation guide.
```bash
docker run --rm --name deeptutor \
-p 127.0.0.1:3782:3782 \
-v deeptutor-data:/app/data \
ghcr.io/hkuds/deeptutor:latest
```
> **Only `3782` needs to be published.** The browser talks exclusively to the frontend origin; the Next.js middleware (`web/proxy.ts`) forwards `/api/*` and `/ws/*` to the FastAPI backend **inside the container**. Publishing `8001` (`-p 127.0.0.1:8001:8001`) is optional — handy only for hitting the API directly with curl or scripts.
Open [http://127.0.0.1:3782](http://127.0.0.1:3782). The container creates `/app/data/user/settings/*.json` on first boot; configure model providers from the Web Settings page. Config, API keys, logs, workspace files, memory, and knowledge bases persist in the `deeptutor-data` volume.
- **Different host ports:** change the left side of each `-p host:container` mapping (e.g. `-p 127.0.0.1:8088:3782`). If you change container-side ports in `/app/data/user/settings/system.json`, restart and update the right side of each mapping to match.
- **Detached:** add `-d`, then `docker logs -f deeptutor` to follow, `docker stop deeptutor` to stop, `docker rm deeptutor` before reusing the name. The `deeptutor-data` volume keeps your settings and workspace across restarts.
**Remote Docker / reverse proxy:** the browser only talks to the frontend
origin (`:3782`); the in-container Next.js middleware forwards `/api/*` and
`/ws/*` to the backend server-side. For the common single-container case you
don't configure an API base at all — just point your reverse proxy / TLS
terminator at `:3782`. You only need an API base for a **split deployment**
(backend in a separate container/host): set `next_public_api_base` in
`data/user/settings/system.json` to the in-network address the frontend server
uses to reach the backend (it's read server-side, never sent to the browser).
```json
{
"next_public_api_base": "http://backend:8001"
}
```
`next_public_api_base_external` (and its alias `public_api_base`) are accepted as
lower-precedence fallbacks. CORS uses frontend **origins**, not API URLs. With
auth disabled, DeepTutor permits normal HTTP/HTTPS browser origins by default.
With auth enabled, add exact frontend origins:
```json
{
"cors_origins": ["https://deeptutor.example.com"]
}
```
<details>
<summary><b>Connecting to Ollama / LM Studio / llama.cpp / vLLM / Lemonade on the host</b></summary>
Inside Docker, `localhost` is the container itself, not your host machine. To reach a model service running on the host, use the host gateway (recommended):
```bash
docker run --rm --name deeptutor \
-p 127.0.0.1:3782:3782 -p 127.0.0.1:8001:8001 \
--add-host=host.docker.internal:host-gateway \
-v deeptutor-data:/app/data \
ghcr.io/hkuds/deeptutor:latest
```
Then in **Settings → Models**, point the provider Base URL at `host.docker.internal`:
- Ollama LLM: `http://host.docker.internal:11434/v1`
- Ollama embedding: `http://host.docker.internal:11434/api/embed`
- LM Studio: `http://host.docker.internal:1234/v1`
- llama.cpp: `http://host.docker.internal:8080/v1`
- Lemonade: `http://host.docker.internal:13305/api/v1`
Docker Desktop (macOS/Windows) usually resolves `host.docker.internal` without `--add-host`. On Linux, the flag is the portable way to create that hostname on modern Docker Engine.
**Linux alternative — host networking:** add `--network=host` and drop the `-p` flags. The container shares the host network directly, so open [http://127.0.0.1:3782](http://127.0.0.1:3782) (or the `frontend_port` in `system.json`), and host services can be reached with normal localhost URLs like `http://127.0.0.1:11434/v1`. Note that host networking exposes container ports directly on the host and may conflict with existing services — to keep them on loopback, set `BACKEND_HOST=127.0.0.1` and `FRONTEND_HOST=127.0.0.1` (see [CONTAINERIZATION.md](./CONTAINERIZATION.md)).
</details>
</details>
<details>
<summary><b>Option 4 — CLI Only</b> · no Web UI, from a source checkout</summary>
When you don't need the Web UI. The CLI-only package is installed from a source checkout, not from PyPI.
```bash
git clone https://github.com/HKUDS/DeepTutor.git
cd DeepTutor
# Create a venv (macOS/Linux). Windows PowerShell:
# py -3.11 -m venv .venv-cli ; .\.venv-cli\Scripts\Activate.ps1
python3 -m venv .venv-cli && source .venv-cli/bin/activate
python -m pip install --upgrade pip
python -m pip install -e ./packaging/deeptutor-cli
deeptutor init --cli
deeptutor chat
```
`deeptutor init --cli` shares the same `data/user/settings/` layout as the full app but skips the backend/frontend port prompts and defaults embeddings to **off** (choose `Yes` if you plan to use `deeptutor kb …` or RAG tools). It still writes a complete runtime layout (`system.json`, `auth.json`, `integrations.json`, `model_catalog.json`, `main.yaml`, `agents.yaml`) and still prompts for the active LLM provider and model.
<details>
<summary><b>Common commands</b></summary>
```bash
deeptutor chat # interactive REPL
deeptutor chat --capability deep_solve --tool rag --kb my-kb
deeptutor run chat "Explain Fourier transform"
deeptutor run deep_solve "Solve x^2 = 4" --tool rag --kb my-kb
deeptutor kb create my-kb --doc textbook.pdf
deeptutor memory show
deeptutor config show
```
</details>
The local `deeptutor-cli` install ships no Web assets or server dependencies. Keep the source checkout around — the editable install points to it. To add the Web app later, install the PyPI package (Option 1) and run `deeptutor init` + `deeptutor start` from the same workspace.
</details>
<details>
<summary><b>Code Execution Sandbox (office skills)</b> · running model-generated code for docx / pdf / pptx / xlsx</summary>
The built-in office skills — **docx / pdf / pptx / xlsx** — work by having the
model write a short Python script (`python-docx`, `reportlab`, `openpyxl`, …),
run it through the `exec` / `code_execution` tools, and hand back a download URL.
Those tools mount whenever a sandbox backend is active, which it is **by default**
in every deployment shape:
- **Local (Option 1 / 2) and Docker (Option 3, single container):** a restricted
subprocess sandbox runs the model's code (on the host locally, or inside the
container under Docker — the container being its own isolation boundary).
- **docker-compose:** routed instead to a hardened, least-privileged **runner
sidecar** (`Dockerfile.runner`) via `DEEPTUTOR_SANDBOX_RUNNER_URL` — the
strongest posture, and preferred automatically when present.
The subprocess sandbox is controlled by the `sandbox_allow_subprocess` setting in
`data/user/settings/system.json` (default `true`). Running model-generated code
on your host is a real trust decision — set it to `false` (or export
`DEEPTUTOR_SANDBOX_ALLOW_SUBPROCESS=0`) to disable host-side execution, at the
cost of the office skills no longer being able to produce files.
</details>
<details>
<summary><b>Configuration reference</b> — config files under <code>data/user/settings/</code> (JSON/YAML)</summary>
Everything under `data/user/settings/` is plain JSON/YAML. The **Settings** page in the browser is the recommended editor.
| File | Purpose |
|:---|:---|
| `model_catalog.json` | LLM, embedding, and search provider profiles; API keys; active models |
| `system.json` | Backend/frontend ports, public API base, CORS, SSL verification, attachment directory |
| `auth.json` | Optional auth toggle, username, password hash, token/cookie settings |
| `integrations.json` | Optional PocketBase and sidecar integration settings |
| `interface.json` | UI language / theme / sidebar preferences |
| `main.yaml` | Runtime behavior defaults and path injection |
| `agents.yaml` | Capability/tool temperature and token settings |
Project-root `.env` is **not** read as an application config file. For a minimal model setup, open **Settings → Models**, add an LLM profile (Base URL / API key / model name), and save. Add an embedding profile only if you plan to use Knowledge Base / RAG features.
</details>
## 📖 Explore DeepTutor
Start with the main surfaces you will use day to day: Chat, Partners, My Agents, Co-Writer, Book, Knowledge Center, Learning Space, Memory, and Settings. The tour then covers Multi-User deployments for shared, isolated workspaces.
<div align="center">
<img src="assets/figs/web-1.4.6+/OVERVIEW.png" alt="DeepTutor home — the Chat workspace with every surface in the sidebar" width="900">
</div>
<details>
<summary><b>🏗️ System architecture</b></summary>
<div align="center">
<img src="assets/figs/system/system%20architecture.png" alt="DeepTutor system architecture" width="900">
</div>
</details>
<details>
<summary><b>💬 Chat — The Agent Loop You Actually Use</b></summary>
Chat is the default capability and where most work begins. A single thread can talk normally, call tools, ground itself in selected knowledge bases, read attachments, generate images, consult subagents, write notebook records, and continue with the same context across turns.
<div align="center">
<img src="assets/figs/web-1.4.6+/home/00-overview.png" alt="DeepTutor chat workspace" width="900">
</div>
The loop is deliberately simple: the model thinks in rounds, calls tools when useful, observes the results, and finishes with a tool-free message. `ask_user` is special — instead of guessing, the agent can pause the turn, ask a structured clarifying question, and resume once you answer.
<div align="center">
<img src="assets/figs/system/chat-agent-loop.png" alt="DeepTutor chat agent loop" width="900">
</div>
User-toggleable tools are `brainstorm`, `web_search`, `paper_search`, `reason`, and `geogebra_analysis` — plus `imagegen` and `videogen` once you configure the matching generation model. Contextual tools such as `rag`, `read_source`, `read_memory`, `write_memory`, `read_skill`, `load_tools`, `exec`, `web_fetch`, `ask_user`, `list_notebook`, `write_note`, `github`, and `consult_subagent` mount automatically when the turn has the right context.
Context comes in two kinds: **sticky session context** (subagent, knowledge bases, persona, model, voice) lives on the composer toolbar and persists across turns; **one-time references** (files, chat history, books, notebooks, question bank, imported agents) come from the `+` menu for a single turn.
Chat is also the launch point for deeper capabilities: **Quiz** for question generation, **Research** for cited reports, **Visualize** for charts / diagrams / animations, and — under *More Capabilities***Solve** for worked reasoning and **Mastery Path** for learning-plan flows.
</details>
<details>
<summary><b>🤝 Partner — Persistent Companions on the Same Brain</b></summary>
<div align="center">
<img src="assets/figs/web-1.4.6+/partners/00-partners%20overview.png" alt="DeepTutor partners workspace" width="900">
</div>
Partners are persistent companions with their own soul, model policy, library, memory, and channels. They are not a separate bot engine: every inbound web or IM message becomes a normal `ChatOrchestrator` turn inside a partner-scoped workspace. A partner is "a chat that has a personality and a phone number."
<div align="center">
<img src="assets/figs/system/partners-architecture.png" alt="DeepTutor partners architecture" width="900">
</div>
Each partner has a `SOUL.md`, model selection, channels, tool policy, and assigned library. Knowledge bases, skills, and notebooks are copied into `data/partners/<id>/workspace/`, so the same RAG, skill, notebook, and memory tools work without special cases. A partner reads its owner's memory but writes only its own.
<div align="center">
<img src="assets/figs/web-1.4.6+/partners/02-IM%20config%20for%20each%20partner.png" alt="Per-partner IM channel configuration" width="900">
</div>
The channel layer is schema-driven and can connect to IM platforms such as Feishu, Telegram, Slack, Discord, DingTalk, QQ/NapCat, WeCom, WhatsApp, Zulip, Mattermost, Matrix, Mochat, and Microsoft Teams depending on installed extras and configured credentials. A partner can also be connected as a subagent and consulted from a normal chat turn — see **My Agents** below.
</details>
<details>
<summary><b>🧑‍🚀 My Agents — Consult & Import Other Agents</b></summary>
<div align="center">
<img src="assets/figs/web-1.4.6+/myagents/00-overview.png" alt="DeepTutor My Agents workspace" width="900">
</div>
My Agents turns other agents into context for DeepTutor, and does two distinct things. **Connect a live agent** — a Claude Code or Codex CLI on your machine, or one of your Partners — and consult it from inside a chat turn: DeepTutor actually *runs* the other agent and streams its work into the Activity panel via the `consult_subagent` tool. Select it with the Agent chip (or type `@`), and set how many rounds the consult may take.
<div align="center">
<img src="assets/figs/web-1.4.6+/home/08-subagent%20demo%20with%20claude%20code.png" alt="Consulting a Claude Code subagent live" width="900">
</div>
**Import past conversations** — bring in your existing Claude Code and Codex history as named, searchable, resumable agents. Pick which days to import; refreshing re-syncs them. Reference an imported conversation from any chat turn via `+` → My Agents, and DeepTutor reads it as a third-party transcript — it stays *their* conversation, not DeepTutor's own voice.
</details>
<details>
<summary><b>✍️ Co-Writer — Selection-Aware Markdown Drafting</b></summary>
<div align="center">
<img src="assets/figs/web-1.4.6+/co-writer/00-overview.png" alt="DeepTutor Co-Writer workspace" width="900">
</div>
Co-Writer is a split-view Markdown workspace for reports, tutorials, notes, and long-form learning artifacts. Documents autosave and render a live preview (KaTeX math, diagram fences), and can be saved back into notebooks when a draft becomes reusable context.
<div align="center">
<img src="assets/figs/web-1.4.6+/co-writer/01-edit%20panel.png" alt="Co-Writer editor with live preview" width="900">
</div>
Its defining idea is **surgical editing**: select a span and ask DeepTutor to rewrite, expand, or shorten it. The edit agent can ground the change in a knowledge base or web evidence, keeps a trace of its tool calls, and shows every change as an accept/reject diff — so nothing lands until you approve it.
</details>
<details>
<summary><b>📖 Book — Living Books from Your Materials</b></summary>
<div align="center">
<img src="assets/figs/web-1.4.6+/book/00-book_overview.png" alt="DeepTutor book library" width="900">
</div>
Book turns selected sources into an interactive **living book** — not a static PDF, but a reading environment built from typed blocks. A book can start from knowledge bases, notebooks, question banks, or chat history; the creation flow proposes a chapter outline before content is generated, so you review the shape instead of accepting a blind one-shot output.
<p align="center">
<img src="assets/figs/web-1.4.6+/book/01-book-demo-quiz%20card.png" alt="Book quiz block" width="31%">
&nbsp;
<img src="assets/figs/web-1.4.6+/book/02-book-demo-manim%20video.png" alt="Book Manim animation block" width="31%">
&nbsp;
<img src="assets/figs/web-1.4.6+/book/03-book-demo%20interactive%20module.png" alt="Book interactive widget block" width="31%">
</p>
Each chapter compiles into typed blocks — text, callouts, quizzes, flash cards, timelines, code, figures, interactive HTML, animations, concept graphs, deep dives, and user notes — and every page has its own Page Chat. Blocks are editable: insert, move, regenerate, or switch a block's type without rewriting the chapter. Maintenance commands such as `deeptutor book health` and `deeptutor book refresh-fingerprints` help detect when source knowledge has drifted from compiled pages.
</details>
<details>
<summary><b>📚 Knowledge Center — Multi-Engine RAG Libraries</b></summary>
<div align="center">
<img src="assets/figs/web-1.4.6+/knowledge/00-overview.png" alt="DeepTutor Knowledge Center" width="900">
</div>
Knowledge bases are the document collections behind RAG — they ground Chat turns, Co-Writer edits, Book generation, and Partner conversations. What's distinctive is a **choice of retrieval engines**: **LlamaIndex** (the default, local vector + BM25), **PageIndex** (hosted, reasoning retrieval with page-level citations), **GraphRAG** and **LightRAG** (knowledge-graph retrieval), **LightRAG Server** (retrieval offloaded to an external LightRAG instance you connect over HTTP), or a linked **Obsidian** vault the tutor reads and writes in place. Each KB is bound to one engine.
<div align="center">
<img src="assets/figs/web-1.4.6+/knowledge/01-create%20knowledge%20base.png" alt="Create a knowledge base" width="900">
</div>
Creating a KB, you either **create new** (upload documents and build a fresh index) or **link existing** (reuse an index built elsewhere, read in place with no re-index). Re-indexing writes a new flat `version-N` directory and keeps prior ones, so a working index is never destroyed mid-rebuild. A single document can be removed even from an **error**-state base — dropping a file that failed to parse without a full delete-and-rebuild. Document parsing — Text-only, MinerU, Docling, markitdown, or PyMuPDF4LLM — is chosen in **Settings → Knowledge Base**, with local model downloads off by default. The CLI mirrors the lifecycle with `deeptutor kb list`, `info`, `create`, `add`, `search`, `set-default`, and `delete`.
</details>
<details>
<summary><b>🌐 Learning Space — Skills, Personas, and Reusable Context</b></summary>
<div align="center">
<img src="assets/figs/web-1.4.6+/learning-space/00-overview.png" alt="DeepTutor Learning Space hub" width="900">
</div>
Learning Space is the library and personalization layer — where the things that persist live. **Conversations & Materials** holds your chat history, notebooks, and a question bank (each saved question keeps your answer, the reference answer, and an explanation). **Personalization** holds mastery paths, personas (behavior presets such as *peer*, *research-assistant*, *teacher*), and skills (`SKILL.md` playbooks the model reads on demand). Everything here can be reused from Chat, Partners, Co-Writer, and Book.
<div align="center">
<img src="assets/figs/web-1.4.6+/learning-space/07-%20download%20skills%20from%20eduhub.png" alt="Import skills from EduHub" width="900">
</div>
You don't have to write every skill yourself — **Import from EduHub** browses the community catalog and downloads a skill straight into your library through a security gate (see [Ecosystem](#-ecosystem--eduhub--the-skills-community)).
</details>
<details>
<summary><b>🧠 Memory — Inspectable Personalization</b></summary>
<div align="center">
<img src="assets/figs/web-1.4.6+/memory/00-overview.png" alt="DeepTutor memory overview" width="900">
</div>
Memory is a file-backed, three-layer system you can read, curate, and audit — deliberately *not* a hidden vector store. **L1** is the workspace mirror plus an append-only event trace (`trace/<surface>/<date>.jsonl`); **L2** is per-surface curated facts (`L2/<surface>.md`); **L3** is cross-surface synthesis (`L3/<profile|recent|scope|preferences>.md`). Because L2 cites L1 and L3 cites L2, nothing in your profile is unaccountable.
<div align="center">
<img src="assets/figs/web-1.4.6+/memory/01-3%20layer%20memory%20graph.png" alt="DeepTutor memory graph" width="900">
</div>
The Memory Graph shows the whole pyramid — L3 synthesis at the centre, L2 in the middle ring, L1 traces on the outside — so you can trace any synthesized claim back to the exact raw event behind it. Memory is tracked across `chat`, `notebook`, `quiz`, `kb`, `book`, partner, and `cowriter` surfaces; the consolidator's Update / Audit / Dedup budgets are tuned in **Settings → Memory**.
</details>
<details>
<summary><b>⚙️ Settings — One Control Plane</b></summary>
<div align="center">
<img src="assets/figs/web-1.4.6+/settings/00-setting%20overview.png" alt="DeepTutor settings hub" width="900">
</div>
Settings is the operational control plane, with a live status strip (Backend, LLM, Embedding, Search) and one card per area: **Appearance** (theme + UI language), **Network** (API base, ports, CORS), **Models** (LLM, Embedding, Search, Text-to-Speech, Speech-to-Text, Image Generation, Video Generation), **Knowledge Base** (document parsing engine), **Chat** (tools, MCP servers, per-capability parameters), **Partners & Agents** (the subagents you can consult from a turn), and **Memory** (the consolidator's budgets).
<div align="center">
<img src="assets/figs/web-1.4.6+/settings/01-appearance%20settings.png" alt="DeepTutor appearance settings and themes" width="900">
</div>
Most sections use a draft-and-apply flow, so you can test a provider before committing it. Four themes ship in the box — Default, Cream, Dark, and Glass. Project-root `.env` files are intentionally ignored; runtime configuration lives under `data/user/settings/*.json` unless `DEEPTUTOR_HOME` or `deeptutor start --home` points the app elsewhere.
</details>
<details>
<summary><b>👥 Multi-User — Shared Deployments</b> · optional auth, isolated per-user workspaces</summary>
Authentication is **off by default** — DeepTutor runs single-user. Turn it on and one `data/` tree hosts an admin workspace, isolated per-user workspaces, and partner workspaces side by side:
```text
data/
├── user/ # Admin workspace + global settings
├── users/<uid>/ # Per-user scope: chat history, memory, notebooks, KBs
├── partners/<id>/workspace/ # Partner (synthetic-user) scope
└── system/ # auth/users.json · grants/<uid>.json · audit/usage.jsonl
```
The **first registered user becomes admin** and owns model catalogs, provider credentials, shared knowledge bases, skills, and per-user grants. Everyone else gets an isolated workspace and a redacted Settings page — admin-assigned models, KBs, and skills show up as scoped, read-only options, never as raw API keys.
**Enable it:** turn auth on in `data/user/settings/auth.json`, restart `deeptutor start`, register the first admin at `/register`, then add users from `/admin/users` and assign models, KBs, skills, partners, tool/MCP policy, and code-execution access through grants.
> PocketBase stays a single-user integration — keep `integrations.pocketbase_url` blank for multi-user deployments unless you've wired up an external user store.
</details>
## ⌨️ DeepTutor CLI — Agent-Native Interface
One `deeptutor` binary, two ways in: an interactive **REPL** for people who live in the terminal, and structured **JSON** for other agents that drive DeepTutor as a tool. Same capabilities, tools, and knowledge bases either way.
<details>
<summary><b>Drive it yourself</b></summary>
`deeptutor chat` opens an interactive REPL; `deeptutor run <capability> "<message>"` fires a single turn and exits. Both speak the same `--capability`, `--tool`, `--kb`, and `--config` flags.
```bash
deeptutor chat # interactive REPL
deeptutor chat --capability deep_solve --kb my-kb --tool rag
deeptutor run chat "Explain the Fourier transform" --tool rag --kb textbook
deeptutor run deep_research "Survey 2026 papers on RAG" \
--config mode=report --config depth=standard
```
Everything the Web app does is here too — knowledge bases (`kb`), sessions (`session`), partners (`partner`), skills (`skill`), notebooks, memory, and config. Full list below.
</details>
<details>
<summary><b>Let an agent drive it</b></summary>
DeepTutor is built to be *operated by another agent*. Add `--format json` to any `run` and each turn streams **NDJSON — one event per line** (`content`, `tool_call`, `tool_result`, `done`, …), every line tagged with its `session_id`. Runs are headless-safe: an `ask_user` pause with no TTY auto-resolves with an empty reply instead of hanging.
```bash
# One shot, machine-readable
deeptutor run deep_solve "Find d/dx[sin(x^2)]" --tool reason --format json
# Chain turns in one stateful session — capture the id, reuse it
SID=$(deeptutor run deep_research "Survey 2026 papers on RAG" \
--config mode=report --config depth=standard --format json \
| jq -r 'select(.type=="done").session_id')
deeptutor run deep_question "Quiz me on that survey" --session "$SID" --format json
```
The repo ships a root [`SKILL.md`](SKILL.md) — a ~150-line handover doc that teaches any tool-using LLM the whole surface in one read. Hand it to Claude Code, Codex, or OpenCode (they pick up `SKILL.md` automatically), or wrap `deeptutor run` as a tool in a LangChain / AutoGen loop. Full recipes: [Agent Handoff](https://deeptutor.info/docs/cli/agent-handoff/).
</details>
<details>
<summary><b>Command reference</b></summary>
| Command | Description |
|:---|:---|
| `deeptutor init` | Create or update `data/user/settings` for the current workspace |
| `deeptutor start [--home PATH]` | Launch backend + frontend together |
| `deeptutor serve [--port PORT]` | Start only the FastAPI backend |
| `deeptutor run <capability> <message>` | Run a single capability turn (`chat`, `deep_solve`, `deep_question`, `deep_research`, `visualize`, `math_animator`, `mastery_path`); add `--format json` for NDJSON output |
| `deeptutor chat` | Interactive REPL with capability, tool, KB, notebook, and history controls |
| `deeptutor partner list/create/start/stop` | Manage IM-connected partners |
| `deeptutor kb list/info/create/add/search/set-default/delete` | Manage LlamaIndex knowledge bases |
| `deeptutor skill search/install/list/remove/login/logout/publish/update` | Manage skills, install from hubs, and publish your own (`eduhub:<slug>` by default, see Ecosystem) |
| `deeptutor memory show/clear` | Inspect L2/L3 memory docs or clear L1/all memory |
| `deeptutor session list/show/open/rename/delete` | Manage shared sessions |
| `deeptutor notebook list/create/show/add-md/replace-md/remove-record` | Manage notebooks from Markdown files |
| `deeptutor book list/health/refresh-fingerprints` | Inspect books and refresh source fingerprints |
| `deeptutor plugin list/info` | Inspect registered tools and capabilities |
| `deeptutor config show` | Print configuration summary |
| `deeptutor provider login <provider>` | Provider auth (`openai-codex` OAuth login; `github-copilot` validates an existing Copilot auth session) |
</details>
<details>
<summary><b>CLI-only distribution</b></summary>
The CLI-only package lives in `packaging/deeptutor-cli`. In this checkout, install it from source:
```bash
python -m pip install -e ./packaging/deeptutor-cli
```
It isn't published to PyPI yet, so the main [Get Started](#-get-started) section keeps the source-install path.
</details>
## 🧩 Ecosystem — EduHub & the Skills Community
DeepTutor skills use the open **Agent-Skills** format — a folder with a `SKILL.md` playbook (YAML frontmatter + Markdown) and optional reference files. Nothing about it is DeepTutor-specific, so any registry that speaks the format becomes a source for your library. DeepTutor ships with **[EduHub](https://eduhub.deeptutor.info/)** — our own education-focused skill registry — wired in as the default hub.
<details>
<summary><b>EduHub — DeepTutor's skill ecosystem</b></summary>
[**EduHub**](https://eduhub.deeptutor.info/) is the community hub DeepTutor launched for sharing teaching-oriented agent skills — Socratic tutors, flashcard builders, essay feedback, exam blueprints, concept explainers, and more. It is built into DeepTutor, so there's nothing to configure: a bare slug or an `eduhub:` prefix resolves to it.
**Find and install** — in the browser, open **Learning Space → Skills → Import from EduHub** to browse the catalog and download a skill straight into your library. From the terminal:
```bash
deeptutor skill search "socratic tutor" # search EduHub (the default hub)
deeptutor skill install socratic-tutor # fetch → verify → register
deeptutor skill install eduhub:socratic-tutor@1.2.0 # pin a hub and a version
deeptutor skill list # local skills with their hub provenance
```
**Publish your own** — package a `SKILL.md` and share it back to the community:
```bash
deeptutor skill login # browser sign-in to EduHub
deeptutor skill publish ./my-skill # interactive: pick a track + tags, then upload
deeptutor skill update # roll back or release a new version
```
EduHub is also a standalone, ClawHub-compatible registry, so agents that aren't DeepTutor (Claude Code, Codex, …) can use it directly through the `eduhub` CLI — `npx eduhub install socratic-tutor`.
</details>
<details>
<summary><b>The import safety gate</b></summary>
Whatever the source, every import passes the **same safety gate** before anything touches your workspace:
- the registry's **security verdict** is checked first — flagged packages are refused unless you pass `--allow-unverified`;
- archives are extracted defensively (zip-slip / zip-bomb guards) behind a text/script **suffix whitelist**, so binaries never land in the workspace;
- frontmatter is normalized to DeepTutor's schema and `always:` is **stripped**, so a downloaded skill can never force itself into every system prompt;
- provenance — hub, version, verdict, and install time — is written to `.hub-lock.json` for audits and updates.
In multi-user deployments, installing is admin-only: a new skill lands in the admin catalog and stays invisible to other users until a grant assigns it, so an admin can vet it before rolling it out.
</details>
<details>
<summary><b>Also compatible with ClawHub</b></summary>
Because DeepTutor speaks the open Agent-Skills format, **[ClawHub](https://clawhub.ai/)** works as a first-class source too — it's built in alongside EduHub. Pick it with the hub prefix:
```bash
deeptutor skill search "git release notes" --hub clawhub
deeptutor skill install clawhub:git-release-notes@1.0.1
```
Add more registries in `settings/skill_hubs.json`: a `type: "clawhub"` entry points at any compatible HTTP API (EduHub and ClawHub both speak it), `type: "command"` wraps whatever fetch CLI a registry ships, and `"default"` chooses the hub used for bare slugs. All of them feed the same import gate.
</details>
## 🌐 Community
### 📮 Contact
DeepTutor is an open-source project led by [Bingxi Zhao](https://github.com/pancacake) within the [HKUDS](https://github.com/HKUDS) Group, and it iterates in a **fully open-source form**, built together with the community. So far, we **DO NOT** have paid online products of any form. Feel free to reach out at **bingxizhao39@gmail.com** for discussions, ideas, or collaboration.
### 🙏 Appreciation
Heartfelt thanks to [**Chao Huang**](https://sites.google.com/view/chaoh), director of the Data Intelligence Lab @ HKU, and to our HKUDS labmates for their warm support — especially [**Jiahao Zhang**](https://github.com/zzhtx258), [**Zirui Guo**](https://github.com/LarFii), and [**Xubin Ren**](https://github.com/Re-bin). We're also deeply grateful to the **open-source community**: your stars, issues, pull requests, and discussions shape DeepTutor every single day.
DeepTutor also stands on the shoulders of outstanding open-source projects that gave us both tools and inspiration:
| Project | Role / Inspiration |
|:---|:---|
| [**LlamaIndex**](https://github.com/run-llama/llama_index) | RAG pipeline and document-indexing backbone |
| [**nanobot**](https://github.com/HKUDS/nanobot) | Ultra-lightweight agent engine that powered the original TutorBot *(HKUDS)* |
| [**LightRAG**](https://github.com/HKUDS/LightRAG) | Simple & fast RAG *(HKUDS)* |
| [**AutoAgent**](https://github.com/HKUDS/AutoAgent) | Zero-code agent framework *(HKUDS)* |
| [**AI-Researcher**](https://github.com/HKUDS/AI-Researcher) | Automated research pipeline *(HKUDS)* |
| [**OpenClaw**](https://github.com/openclaw/openclaw) | Open agent gateway and skill ecosystem behind ClawHub |
| [**Codex**](https://github.com/openai/codex) | Agent-native coding CLI that inspired our CLI workflow |
| [**Claude Code**](https://github.com/anthropics/claude-code) | Agentic coding CLI that inspired the DeepTutor agent loop |
| [**ManimCat**](https://github.com/Wing900/ManimCat) | AI-driven math animation generation for Math Animator |
### 🗺️ Roadmap & Contribute
We want DeepTutor to keep iterating and improving — and ultimately to become a gift we give back to the open-source community. Our [**roadmap**](https://github.com/HKUDS/DeepTutor/issues/498) is updated continuously; vote on items there or propose new ones. If you'd like to contribute, see the [**Contributing Guide**](CONTRIBUTING.md) for branching strategy, coding standards, and how to get started.
<div align="center">
We hope DeepTutor becomes a gift for the community. 🎁
<a href="https://github.com/HKUDS/DeepTutor/graphs/contributors">
<img src="https://contrib.rocks/image?repo=HKUDS/DeepTutor&max=999" alt="Contributors" />
</a>
</div>
<div align="center">
<a href="https://www.star-history.com/#HKUDS/DeepTutor&type=timeline&legend=top-left">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=HKUDS/DeepTutor&type=timeline&theme=dark&legend=top-left" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=HKUDS/DeepTutor&type=timeline&legend=top-left" />
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=HKUDS/DeepTutor&type=timeline&legend=top-left" />
</picture>
</a>
</div>
<p align="center">
<a href="https://www.star-history.com/hkuds/deeptutor">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/badge?repo=HKUDS/DeepTutor&theme=dark" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/badge?repo=HKUDS/DeepTutor" />
<img alt="Star History Rank" src="https://api.star-history.com/badge?repo=HKUDS/DeepTutor" />
</picture>
</a>
</p>
<div align="center">
Licensed under the [Apache License 2.0](LICENSE).
<p>
<img src="https://visitor-badge.laobi.icu/badge?page_id=HKUDS.DeepTutor&style=for-the-badge&color=00d4ff" alt="Views">
</p>
</div>
+7
View File
@@ -0,0 +1,7 @@
# WeHub 来源说明
- 原始项目:`HKUDS/DeepTutor`
- 原始仓库:https://github.com/HKUDS/DeepTutor
- 导入方式:上游默认分支的最新快照
- 原作者、版权和许可证信息以原始仓库及本仓库 LICENSE 为准
- 本文件仅用于记录来源,不代表 WeHub 是原项目作者
+203
View File
@@ -0,0 +1,203 @@
# DeepTutor CLI Skill
> Teach your AI agent to configure, manage, and use DeepTutor — an intelligent learning platform — entirely through the command line.
## When to Use
Use this skill when the user wants to:
- Set up or configure DeepTutor
- Chat with DeepTutor or run a capability (deep solve, quiz generation, deep research, visualize, math animation, mastery path)
- Create, manage, or search knowledge bases
- Create, manage, or run Partners (IM-connected companions)
- Search, install, or manage skills from a hub (ClawHub)
- Inspect or maintain interactive Books
- View or manage learning memory, sessions, or notebooks
- Start the DeepTutor API server or the full Web app
## Prerequisites
- Python 3.11+
- DeepTutor installed: `pip install deeptutor` for the full Web app, `pip install deeptutor-cli` for CLI-only, or `pip install -e .` from a source checkout
- Run `deeptutor init` for first-time interactive setup. It walks a guided wizard (ports → LLM → embedding → search → review) and writes the same settings as the Web Settings page under `data/user/settings`. Add `--cli` to skip the ports step for CLI-only use, or `--home <path>` to target a specific workspace.
## Commands
### Chat & Capabilities
```bash
# Interactive REPL
deeptutor chat
deeptutor chat --capability deep_solve --kb my-kb --tool rag --tool web_search
# One-shot capability execution
deeptutor run chat "Explain Fourier transform"
deeptutor run deep_solve "Solve x^2 = 4" --tool rag --kb textbook
deeptutor run deep_question "Linear algebra" --config num_questions=5
deeptutor run deep_research "Attention mechanisms" --kb papers --config mode=report --config depth=standard
deeptutor run visualize "Plot the unit circle"
deeptutor run math_animator "Visualize a Fourier series"
# Capabilities accepted by `run` / `chat -c`:
# chat, deep_solve, deep_question, deep_research, visualize, math_animator, mastery_path
# Options for `run`:
# --session <id> Resume existing session
# --tool/-t <name> Enable tool (repeatable)
# --kb <name> Knowledge base (repeatable)
# --notebook-ref <ref> Notebook reference, "<notebook_id>:<rec1>,<rec2>" (repeatable)
# --history-ref <id> Referenced session id (repeatable)
# --language/-l <code> Response language (default: en)
# --config <key=value> Capability config (repeatable)
# --config-json <json> Capability config as JSON
# --format/-f <fmt> Output format: rich | json (default: rich)
```
`deeptutor chat` accepts the same `--session / --tool / --kb / --notebook-ref / --history-ref / --language / --config / --config-json` options, plus `--capability/-c <name>` to set the initial capability.
**Tools** for `--tool` / `-t`: user-toggleable tools are `brainstorm`, `web_search`, `paper_search`, `reason`, `geogebra_analysis`, `imagegen`, and `videogen`. Context-gated tools (`rag`, `code_execution`, `read_source`, `web_fetch`, `github`, `ask_user`, …) auto-mount when their context is present, but can also be force-enabled with `--tool`. Run `deeptutor plugin list` for the full registered set.
### Knowledge Bases
```bash
deeptutor kb list [--format rich|json] # List all knowledge bases
deeptutor kb info <name> # Show knowledge base details (JSON)
deeptutor kb create <name> --doc file.pdf # Create from documents (--doc/-d repeatable)
deeptutor kb create <name> --docs-dir ./papers # ...or from a directory of documents
deeptutor kb add <name> --doc more.pdf # Add documents incrementally
deeptutor kb search <name> "query text" [--mode hybrid] [--format rich|json]
deeptutor kb set-default <name> # Set as default KB
deeptutor kb delete <name> [--force] # Delete a knowledge base
```
### Partners
Partners are IM-connected learning companions (the former "TutorBot").
```bash
deeptutor partner list # List all partners
deeptutor partner create <id> -n "My Tutor" # Create and start a new partner
# -n/--name <text> Display name
# -s/--soul <md> Soul markdown (the persona)
# -m/--model <id> Model override
deeptutor partner start <id> # Start a partner
deeptutor partner stop <id> # Stop a running partner
```
### Skills
Install and manage skills, including packages from external hubs (ClawHub).
Hub refs use `<hub>:<slug>[@version]` (the hub prefix defaults to `clawhub`).
```bash
deeptutor skill search "flashcards" [--hub clawhub] [--limit 10]
deeptutor skill install clawhub:some-skill[@1.2.0] [--name local-name] [--force] [--allow-unverified]
deeptutor skill list # List local skills (with hub provenance)
deeptutor skill remove <name> # Remove a user-layer skill
```
### Books
Maintenance commands for the BookEngine (authoring/reading is via the Web app).
```bash
deeptutor book list # List all books (flags stale pages)
deeptutor book health <book_id> # Inspect KB drift + log.md health
deeptutor book refresh-fingerprints <book_id> # Re-snapshot KB fingerprints
```
### Memory
```bash
deeptutor memory show [<target>] # target: L3 (all global docs, default) | L2 (all surfaces) | a doc name (e.g. profile, chat)
deeptutor memory clear [<target>] # target: all (default) | trace (all L1) | a surface name (clears that surface's L1)
# --force/-f Skip confirmation
```
### Sessions
```bash
deeptutor session list [--limit 20] # List sessions
deeptutor session show <id> [--format rich|json] # View session messages
deeptutor session open <id> # Resume session in the REPL
deeptutor session rename <id> --title "..." # Rename a session
deeptutor session delete <id> # Delete a session
```
### Notebooks
```bash
deeptutor notebook list # List notebooks
deeptutor notebook create <name> [--description "..."]
deeptutor notebook show <notebook_id> [--format rich|json]
deeptutor notebook add-md <notebook_id> <file.md> [--title "..."] [--type chat|question|research|solve]
deeptutor notebook replace-md <notebook_id> <record_id> <file.md>
deeptutor notebook remove-record <notebook_id> <record_id>
```
### Providers
```bash
deeptutor provider login openai-codex # OAuth login for OpenAI Codex
deeptutor provider login github-copilot # Validate an existing Copilot auth session
```
### System
```bash
deeptutor config show # Print resolved configuration
deeptutor plugin list # List registered tools and capabilities
deeptutor plugin info <name> # Show a tool/capability's schema + availability
deeptutor serve [--host 0.0.0.0] [--port 8001] [--reload] # Start the API server
deeptutor start [--home <path>] # Launch backend + frontend together
deeptutor init [--cli] [--home <path>] # Create/update workspace settings
```
## REPL Slash Commands
Inside `deeptutor chat`, use these:
| Command | Effect |
|:---|:---|
| `/quit` | Exit REPL |
| `/session` | Show current session id |
| `/status` | Print the current REPL state |
| `/new` or `/clear` | Start a new session context |
| `/regenerate` or `/retry` | Re-run the last user message |
| `/tool on\|off <name>` | Toggle a tool |
| `/cap <name>` | Switch capability |
| `/kb <name>\|none` | Set or clear knowledge base |
| `/history add <id>` / `/history clear` | Manage history references |
| `/notebook add <ref>` / `/notebook clear` | Manage notebook references |
| `/show last\|<n>` | Expand a captured tool result or thinking block |
| `/refs` | Show all active references |
| `/config show\|set\|clear` | Manage capability config |
## Typical Workflows
**First-time setup:**
```bash
cd DeepTutor
pip install -e .
deeptutor init # Interactive guided setup (add --cli for CLI-only)
```
**Daily learning:**
```bash
deeptutor chat --kb textbook --tool rag --tool web_search
```
**Build a knowledge base from documents:**
```bash
deeptutor kb create physics --doc ch1.pdf --doc ch2.pdf
deeptutor run chat "Explain Newton's third law" --kb physics --tool rag
```
**Generate quiz questions:**
```bash
deeptutor run deep_question "Thermodynamics" --kb physics --config num_questions=5
```
**Run the full Web app locally:**
```bash
deeptutor start # backend + frontend; Ctrl+C to stop
```
+707
View File
@@ -0,0 +1,707 @@
<div align="center">
<p align="center"><img src="../../assets/figs/logo/logo.png" alt="شعار DeepTutor" height="56" style="vertical-align: middle;">&nbsp;<img src="../../assets/figs/logo/banner.png" alt="DeepTutor" height="48" style="vertical-align: middle;"></p>
# DeepTutor: تدريس شخصي مدى الحياة
<p align="center">
<a href="https://deeptutor.info" target="_blank"><img alt="الوثائق — deeptutor.info" src="https://img.shields.io/badge/Docs-deeptutor.info%20%E2%86%97-0A0A0A?style=for-the-badge&labelColor=F5F5F4" height="36"></a>
</p>
<p align="center">
<a href="https://trendshift.io/repositories/17099?utm_source=repository-badge&amp;utm_medium=badge&amp;utm_campaign=badge-repository-17099" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/repositories/17099" alt="HKUDS%2FDeepTutor | Trendshift" width="250" height="55"/></a>&nbsp;
<a href="https://trendshift.io/repositories/17099?utm_source=trendshift-badge&amp;utm_medium=badge&amp;utm_campaign=badge-trendshift-17099" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/17099/daily" alt="HKUDS%2FDeepTutor | Trendshift" width="250" height="55"/></a>&nbsp;
<a href="https://trendshift.io/repositories/17099?utm_source=trendshift-badge&amp;utm_medium=badge&amp;utm_campaign=badge-trendshift-17099" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/17099/weekly?language=Python" alt="HKUDS%2FDeepTutor | Trendshift" width="250" height="55"/></a>
</p>
<p align="center">
<a href="../../README.md"><img alt="English" height="40" src="https://img.shields.io/badge/English-CDCFD4"></a>&nbsp;
<a href="README_CN.md"><img alt="简体中文" height="40" src="https://img.shields.io/badge/简体中文-CDCFD4"></a>&nbsp;
<a href="README_JA.md"><img alt="日本語" height="40" src="https://img.shields.io/badge/日本語-CDCFD4"></a>&nbsp;
<a href="README_ES.md"><img alt="Español" height="40" src="https://img.shields.io/badge/Español-CDCFD4"></a>&nbsp;
<a href="README_FR.md"><img alt="Français" height="40" src="https://img.shields.io/badge/Français-CDCFD4"></a>&nbsp;
<a href="README_AR.md"><img alt="Arabic" height="40" src="https://img.shields.io/badge/Arabic-BCDCF7"></a>&nbsp;
<a href="README_RU.md"><img alt="Русский" height="40" src="https://img.shields.io/badge/Русский-CDCFD4"></a>&nbsp;
<a href="README_HI.md"><img alt="Hindi" height="40" src="https://img.shields.io/badge/Hindi-CDCFD4"></a>&nbsp;
<a href="README_PT.md"><img alt="Português" height="40" src="https://img.shields.io/badge/Português-CDCFD4"></a>&nbsp;
<a href="README_TH.md"><img alt="Thai" height="40" src="https://img.shields.io/badge/Thai-CDCFD4"></a>&nbsp;
<a href="README_PL.md"><img alt="Polski" height="40" src="https://img.shields.io/badge/Polski-CDCFD4"></a>
</p>
[![Python 3.11+](https://img.shields.io/badge/Python-3.11%2B-3776AB?style=flat-square&logo=python&logoColor=white)](https://www.python.org/downloads/)
[![Next.js 16](https://img.shields.io/badge/Next.js-16-000000?style=flat-square&logo=next.js&logoColor=white)](https://nextjs.org/)
[![License](https://img.shields.io/badge/License-Apache_2.0-blue?style=flat-square)](../../LICENSE)
[![GitHub release](https://img.shields.io/github/v/release/HKUDS/DeepTutor?style=flat-square&color=brightgreen)](https://github.com/HKUDS/DeepTutor/releases)
[![arXiv](https://img.shields.io/badge/arXiv-2604.26962-b31b1b?style=flat-square&logo=arxiv&logoColor=white)](https://arxiv.org/abs/2604.26962)
[![Discord](https://img.shields.io/badge/Discord-Community-5865F2?style=flat-square&logo=discord&logoColor=white)](https://discord.gg/eRsjPgMU4t)
[![Feishu](https://img.shields.io/badge/Feishu-Group-00D4AA?style=flat-square&logo=feishu&logoColor=white)](../../Communication.md)
[![WeChat](https://img.shields.io/badge/WeChat-Group-07C160?style=flat-square&logo=wechat&logoColor=white)](https://github.com/HKUDS/DeepTutor/issues/78)
[الميزات](#-الميزات-الرئيسية) · [البدء](#-البدء) · [الاستكشاف](#-استكشاف-deeptutor) · [واجهة CLI](#️-واجهة-سطر-أوامر-deeptutor--الواجهة-الأصيلة-للوكلاء) · [النظام البيئي](#-النظام-البيئي--eduhub-ومجتمع-المهارات) · [المجتمع](#-المجتمع)
</div>
---
> 🤝 **نرحب بجميع أنواع المساهمات!** صوّت على عناصر خارطة الطريق أو اقترح عناصر جديدة في [`خارطة الطريق`](https://github.com/HKUDS/DeepTutor/issues/498)، وراجع [دليل المساهمة](../../CONTRIBUTING.md) لمعرفة استراتيجية الفروع ومعايير البرمجة وكيفية البدء.
### 📰 الأخبار
- **2026-05-22** 🌐 موقع الوثائق الرسمي متاح على [**deeptutor.info**](https://deeptutor.info/) — الأدلة والمراجع وجولات القدرات كلها في مكان واحد.
- **2026-04-19** 🎉 20 ألف نجمة في 111 يومًا! شكراً على الدعم نحو تدريس شخصي وذكي حقيقي.
- **2026-04-10** 📄 ورقتنا البحثية متاحة على arXiv — اقرأ [النسخة الأولية](https://arxiv.org/abs/2604.26962) للتعرف على التصميم والأفكار وراء DeepTutor.
- **2026-02-06** 🚀 10 آلاف نجمة في 39 يومًا فقط! شكر جزيل لمجتمعنا الرائع.
- **2026-01-01** 🎊 كل عام وأنتم بخير! انضم إلى [Discord](https://discord.gg/eRsjPgMU4t) أو [WeChat](https://github.com/HKUDS/DeepTutor/issues/78) أو [النقاشات](https://github.com/HKUDS/DeepTutor/discussions) — لنشكّل معاً مستقبل DeepTutor.
- **2025-12-29** 🎓 تم إطلاق DeepTutor رسميًا!
## ✨ الميزات الرئيسية
DeepTutor هو بيئة تعلم أصيلة للوكلاء تربط التدريس وحل المشكلات وتوليد الاختبارات والبحث والتصور وممارسة الإتقان في نظام واحد قابل للتوسيع.
- **بيئة تشغيل واحدة لجميع الأوضاع** — Chat وQuiz وResearch وVisualize وSolve وMastery Path تعمل على نفس حلقة الوكيل، لذا تغيّر الهدف لا المحرك، والسياق يتبع المتعلم.
- **سياق تعلم متصل** — قواعد المعرفة والكتب ومسودات Co-Writer ودفاتر الملاحظات وبنوك الأسئلة والشخصيات والذاكرة متاحة في جميع سير العمل بدلاً من العيش في أدوات معزولة.
- **الوكلاء الفرعيون والشركاء** — استشارة Claude Code أو Codex أو Partner مباشرةً من أي دور (أو استيراد محادثاتهم السابقة)، وتشغيل رفاق IM دائمين على نفس الدماغ.
- **معرفة متعددة المحركات** — مكتبات RAG مُصدَّرة عبر LlamaIndex وPageIndex وGraphRAG وLightRAG أو مخزن Obsidian مرتبط، مع تحليل مستندات قابل للتوصيل.
- **أدوات ومهارات قابلة للتوسيع** — أدوات مدمجة وخوادم MCP ونماذج توليد الصور/الفيديو/الصوت ومهارات مجتمع قابلة للتثبيت من EduHub.
- **ذاكرة قابلة للتدقيق** — آثار L1 وملخصات سطحية L2 وتركيب L3 تجعل التخصيص مرئياً وقابلاً للتحرير، مع Memory Graph يتتبع كل ادعاء إلى دليله.
---
## 🚀 البدء
يأتي DeepTutor بأربعة مسارات تثبيت. وكلها تشترك في تخطيط مساحة عمل واحد: تعيش الإعدادات في `data/user/settings/` تحت الدليل الذي تُطلق منه التطبيق (أو تحت `DEEPTUTOR_HOME` / `deeptutor start --home` إذا حددت واحداً صراحةً). للتطبيق الكامل، التدفق الموصى به هو **اختر دليل مساحة عمل → تثبيت → `deeptutor init` → `deeptutor start`**.
<details>
<summary><b>الخيار 1 — التثبيت من PyPI</b> · تطبيق ويب محلي كامل + CLI، لا يلزم الاستنساخ</summary>
تطبيق ويب محلي كامل + CLI، لا يلزم الاستنساخ. يحتاج **Python 3.11+** وبيئة تشغيل **Node.js 20+** في PATH (يُشغَّل خادم Next.js المستقل المُحزَّم بواسطة `deeptutor start`).
```bash
mkdir -p my-deeptutor && cd my-deeptutor
pip install -U deeptutor
deeptutor init # يطلب المنافذ + مزود LLM + تضمين اختياري
deeptutor start # يشغّل الخلفية + الواجهة الأمامية؛ ابقِ الطرفية مفتوحة
```
يطلب `deeptutor init` منفذ الخلفية (افتراضي `8001`)، ومنفذ الواجهة الأمامية (افتراضي `3782`)، ومزود LLM / عنوان URL الأساسي / مفتاح API / النموذج، ومزود تضمين اختياري لقاعدة المعرفة / RAG.
بعد `deeptutor start`، افتح عنوان URL للواجهة الأمامية المطبوع في الطرفية — افتراضياً [http://127.0.0.1:3782](http://127.0.0.1:3782). اضغط `Ctrl+C` في تلك الطرفية لإيقاف الخلفية والواجهة الأمامية معاً. تخطي `deeptutor init` لا بأس به للتجربة السريعة؛ يُقلع التطبيق بالمنافذ الافتراضية وإعدادات نموذج فارغة، قم بتهيئتها لاحقاً في **الإعدادات ← النماذج**.
</details>
<details>
<summary><b>الخيار 2 — التثبيت من المصدر</b> · للتطوير مقابل نسخة مسحوبة</summary>
للتطوير مقابل نسخة مسحوبة. استخدم **Python 3.11+** و**Node.js 22 LTS** لمطابقة CI وDocker.
```bash
git clone https://github.com/HKUDS/DeepTutor.git
cd DeepTutor
# إنشاء venv (macOS/Linux). Windows PowerShell:
# py -3.11 -m venv .venv ; .\.venv\Scripts\Activate.ps1
python3 -m venv .venv && source .venv/bin/activate
python -m pip install --upgrade pip
# تثبيت تبعيات الخلفية والواجهة الأمامية
python -m pip install -e .
( cd web && npm ci --legacy-peer-deps )
deeptutor init
deeptutor start
```
تشغّل تثبيتات المصدر Next.js في وضع التطوير مقابل دليل `web/` المحلي؛ كل شيء آخر (تخطيط التهيئة، المنافذ، الإيقاف بـ `Ctrl+C`) يطابق الخيار 1.
<details>
<summary><b>بيئة Conda</b> (بديلاً عن <code>venv</code>)</summary>
```bash
conda create -n deeptutor python=3.11
conda activate deeptutor
python -m pip install --upgrade pip
```
</details>
<details>
<summary><b>إضافات التثبيت الاختيارية</b> — dev / partners / matrix / math-animator</summary>
```bash
pip install -e ".[dev]" # أدوات الاختبار/الفحص
pip install -e ".[partners]" # SDK قنوات شركاء IM + عميل MCP
pip install -e ".[matrix]" # قناة Matrix بدون E2EE/libolm
pip install -e ".[matrix-e2e]" # Matrix E2EE؛ يتطلب libolm
pip install -e ".[math-animator]" # إضافة Manim؛ تتطلب LaTeX/ffmpeg/مكتبات النظام
```
</details>
<details>
<summary><b>تعديلات تبعيات الواجهة الأمامية وحل مشاكل خادم التطوير</b></summary>
**تغيير تبعيات الواجهة الأمامية:** شغّل `npm install --legacy-peer-deps` لتحديث `web/package-lock.json`، ثم ارفع كلاً من `web/package.json` و`web/package-lock.json`.
**خادم تطوير متوقف:** إذا أبلغ `deeptutor start` عن واجهة أمامية موجودة لا تستجيب، أوقف الـ PID الذي يطبعه. إذا لم يكن هناك أي عملية Next.js تعمل فعلياً، فملفات القفل قديمة — احذفها وأعد المحاولة:
```bash
rm -f web/.next/dev/lock web/.next/lock
deeptutor start
```
</details>
</details>
<details>
<summary><b>الخيار 3 — Docker</b> · حاوية واحدة مكتفية بذاتها</summary>
حاوية واحدة لتطبيق الويب الكامل. الصور على GitHub Container Registry:
- `ghcr.io/hkuds/deeptutor:latest` — إصدار مستقر
- `ghcr.io/hkuds/deeptutor:pre` — إصدار تجريبي، عند توفره
> راجع [CONTAINERIZATION.md](../../CONTAINERIZATION.md) لعمليات نشر podman/rootless/read-only-rootfs والدليل الكامل لكل تثبيت.
```bash
docker run --rm --name deeptutor \
-p 127.0.0.1:3782:3782 \
-v deeptutor-data:/app/data \
ghcr.io/hkuds/deeptutor:latest
```
> **يكفي نشر `3782` فقط.** يتحدث المتصفح حصرياً إلى أصل الواجهة الأمامية؛ يقوم وسيط Next.js (`web/proxy.ts`) بإعادة توجيه `/api/*` و`/ws/*` إلى خلفية FastAPI **داخل الحاوية**. نشر `8001` (`-p 127.0.0.1:8001:8001`) اختياري — مفيد فقط لاستدعاء واجهة برمجة التطبيقات مباشرةً باستخدام curl أو نصوص.
افتح [http://127.0.0.1:3782](http://127.0.0.1:3782). تُنشئ الحاوية `/app/data/user/settings/*.json` عند الإقلاع الأول؛ قم بتهيئة مزودي النماذج من صفحة إعدادات الويب. تبقى التهيئة ومفاتيح API والسجلات وملفات مساحة العمل والذاكرة وقواعد المعرفة في وحدة تخزين `deeptutor-data`.
- **منافذ مضيف مختلفة:** غيّر الجانب الأيسر من كل تعيين `-p host:container` (مثلاً `-p 127.0.0.1:8088:3782`). إذا غيّرت المنافذ على جانب الحاوية في `/app/data/user/settings/system.json`، أعد التشغيل وحدّث الجانب الأيمن من كل تعيين ليطابق ذلك.
- **وضع المنفصل:** أضف `-d`، ثم `docker logs -f deeptutor` للمتابعة، و`docker stop deeptutor` للإيقاف، و`docker rm deeptutor` قبل إعادة استخدام الاسم. تحتفظ وحدة تخزين `deeptutor-data` بإعداداتك ومساحة عملك عبر إعادات التشغيل.
**Docker عن بُعد / وكيل عكسي:** يتحدث المتصفح فقط إلى أصل الواجهة الأمامية (`:3782`)؛ يقوم وسيط Next.js داخل الحاوية بإعادة توجيه `/api/*` و`/ws/*` إلى خادم الخلفية من جانب الخادم. في حالة الحاوية الواحدة الشائعة لا تهيّئ قاعدة API على الإطلاق — فقط وجّه وكيلك العكسي / منهي TLS إلى `:3782`. تحتاج قاعدة API فقط لـ **النشر المنفصل** (الخلفية في حاوية/مضيف منفصل): اضبط `next_public_api_base` في `data/user/settings/system.json` على عنوان الشبكة الداخلية الذي يستخدمه خادم الواجهة الأمامية للوصول إلى الخلفية (يُقرأ من جانب الخادم، ولا يُرسَل أبداً إلى المتصفح).
```json
{
"next_public_api_base": "http://backend:8001"
}
```
يُقبَل `next_public_api_base_external` (واسمه المستعار `public_api_base`) كبدائل ذات أولوية أقل. يستخدم CORS **منشآت** الواجهة الأمامية، وليس عناوين URL لواجهة برمجة التطبيقات. مع تعطيل المصادقة، يسمح DeepTutor بمنشآت متصفح HTTP/HTTPS العادية افتراضياً. مع تفعيل المصادقة، أضف منشآت الواجهة الأمامية الدقيقة:
```json
{
"cors_origins": ["https://deeptutor.example.com"]
}
```
<details>
<summary><b>الاتصال بـ Ollama / LM Studio / llama.cpp / vLLM / Lemonade على المضيف</b></summary>
داخل Docker، يشير `localhost` إلى الحاوية نفسها، وليس جهازك المضيف. للوصول إلى خدمة نموذج تعمل على المضيف، استخدم بوابة المضيف (موصى بها):
```bash
docker run --rm --name deeptutor \
-p 127.0.0.1:3782:3782 -p 127.0.0.1:8001:8001 \
--add-host=host.docker.internal:host-gateway \
-v deeptutor-data:/app/data \
ghcr.io/hkuds/deeptutor:latest
```
ثم في **الإعدادات ← النماذج**، وجّه عنوان URL الأساسي للمزود إلى `host.docker.internal`:
- Ollama LLM: `http://host.docker.internal:11434/v1`
- Ollama embedding: `http://host.docker.internal:11434/api/embed`
- LM Studio: `http://host.docker.internal:1234/v1`
- llama.cpp: `http://host.docker.internal:8080/v1`
- Lemonade: `http://host.docker.internal:13305/api/v1`
عادةً ما يحل Docker Desktop (macOS/Windows) `host.docker.internal` بدون `--add-host`. على Linux، يُعدّ هذا العلم الطريقة المحمولة لإنشاء هذا الاسم المضيف على Docker Engine الحديث.
**بديل Linux — شبكة المضيف:** أضف `--network=host` وأزل علامات `-p`. تشارك الحاوية شبكة المضيف مباشرةً، لذا افتح [http://127.0.0.1:3782](http://127.0.0.1:3782) (أو `frontend_port` في `system.json`)، ويمكن الوصول إلى خدمات المضيف بعناوين URL العادية لـ localhost مثل `http://127.0.0.1:11434/v1`. لاحظ أن شبكة المضيف تكشف منافذ الحاوية مباشرةً على المضيف وقد تتعارض مع الخدمات الموجودة — للإبقاء عليها على loopback، اضبط `BACKEND_HOST=127.0.0.1` و`FRONTEND_HOST=127.0.0.1` (راجع [CONTAINERIZATION.md](../../CONTAINERIZATION.md)).
</details>
</details>
<details>
<summary><b>الخيار 4 — واجهة سطر الأوامر فقط</b> · بدون واجهة ويب، من نسخة مسحوبة</summary>
عندما لا تحتاج إلى واجهة مستخدم الويب. يُثبَّت حزمة CLI فقط من نسخة مسحوبة من المصدر، وليس من PyPI.
```bash
git clone https://github.com/HKUDS/DeepTutor.git
cd DeepTutor
# إنشاء venv (macOS/Linux). Windows PowerShell:
# py -3.11 -m venv .venv-cli ; .\.venv-cli\Scripts\Activate.ps1
python3 -m venv .venv-cli && source .venv-cli/bin/activate
python -m pip install --upgrade pip
python -m pip install -e ./packaging/deeptutor-cli
deeptutor init --cli
deeptutor chat
```
يشارك `deeptutor init --cli` نفس تخطيط `data/user/settings/` مع التطبيق الكامل لكنه يتخطى موجهات منفذ الخلفية/الواجهة الأمامية ويضبط التضمينات افتراضياً على **إيقاف** (اختر `نعم` إذا كنت تخطط لاستخدام `deeptutor kb …` أو أدوات RAG). لا يزال يكتب تخطيط وقت تشغيل كامل (`system.json`، `auth.json`، `integrations.json`، `model_catalog.json`، `main.yaml`، `agents.yaml`) ولا يزال يطلب مزود LLM النشط والنموذج.
<details>
<summary><b>الأوامر الشائعة</b></summary>
```bash
deeptutor chat # REPL تفاعلي
deeptutor chat --capability deep_solve --tool rag --kb my-kb
deeptutor run chat "Explain Fourier transform"
deeptutor run deep_solve "Solve x^2 = 4" --tool rag --kb my-kb
deeptutor kb create my-kb --doc textbook.pdf
deeptutor memory show
deeptutor config show
```
</details>
لا يشحن تثبيت `deeptutor-cli` المحلي بأصول الويب أو تبعيات الخادم. احتفظ بالنسخة المسحوبة من المصدر — يشير التثبيت القابل للتحرير إليها. لإضافة تطبيق الويب لاحقاً، ثبّت حزمة PyPI (الخيار 1) وشغّل `deeptutor init` + `deeptutor start` من نفس مساحة العمل.
</details>
<details>
<summary><b>صندوق أمان تنفيذ الرمز (مهارات المكتب)</b> · تشغيل الرمز المُولَّد بالنموذج لـ docx / pdf / pptx / xlsx</summary>
مهارات المكتب المدمجة — **docx / pdf / pptx / xlsx** — تعمل عن طريق جعل النموذج يكتب برنامج Python قصير (`python-docx`، `reportlab`، `openpyxl`، ...)، وتشغيله عبر أدوات `exec` / `code_execution`، وإرجاع عنوان URL للتنزيل. تُثبَّت هذه الأدوات عندما تكون خلفية صندوق الأمان نشطة، وهي كذلك **افتراضياً** في كل شكل نشر:
- **محلي (الخيار 1 / 2) وDocker (الخيار 3، حاوية واحدة):** يُشغَّل صندوق أمان عمليات فرعية مقيّدة لرمز النموذج (على المضيف محلياً، أو داخل الحاوية تحت Docker — والحاوية هي حدود عزلها الخاصة).
- **docker-compose:** يُوجَّه بدلاً من ذلك إلى **مرافق runner** محصَّن وأقل امتيازاً (`Dockerfile.runner`) عبر `DEEPTUTOR_SANDBOX_RUNNER_URL` — أقوى وضع، ويُفضَّل تلقائياً عند توفره.
يتحكم إعداد `sandbox_allow_subprocess` في `data/user/settings/system.json` (افتراضي `true`) في صندوق أمان العمليات الفرعية. تشغيل الرمز المُولَّد بواسطة النموذج على مضيفك هو قرار ثقة حقيقي — اضبطه على `false` (أو صدّر `DEEPTUTOR_SANDBOX_ALLOW_SUBPROCESS=0`) لتعطيل التنفيذ على جانب المضيف، على حساب عدم قدرة مهارات المكتب على إنتاج الملفات بعد الآن.
</details>
<details>
<summary><b>مرجع التهيئة</b> — ملفات التهيئة تحت <code>data/user/settings/</code> (JSON/YAML)</summary>
كل شيء تحت `data/user/settings/` هو JSON/YAML عادي. صفحة **الإعدادات** في المتصفح هي المحرر الموصى به.
| الملف | الغرض |
|:---|:---|
| `model_catalog.json` | ملفات تعريف مزودي النماذج اللغوية الكبيرة والتضمين والبحث؛ مفاتيح API؛ النماذج النشطة |
| `system.json` | منافذ الخلفية/الواجهة الأمامية، وقاعدة API العامة، وCORS، والتحقق من SSL، ودليل المرفقات |
| `auth.json` | تبديل مصادقة اختياري، واسم مستخدم، وتجزئة كلمة مرور، وإعدادات الرمز/الكوكي |
| `integrations.json` | إعدادات تكامل PocketBase والمرافق الاختيارية |
| `interface.json` | تفضيلات لغة واجهة المستخدم / الثيمة / الشريط الجانبي |
| `main.yaml` | افتراضيات سلوك وقت التشغيل وحقن المسار |
| `agents.yaml` | إعدادات درجة حرارة القدرة/الأداة والرمز |
ملف `.env` في جذر المشروع **لا يُقرأ** كملف تهيئة للتطبيق. للإعداد الأدنى للنموذج، افتح **الإعدادات ← النماذج**، أضف ملف تعريف LLM (عنوان URL الأساسي / مفتاح API / اسم النموذج)، واحفظ. أضف ملف تعريف التضمين فقط إذا كنت تخطط لاستخدام ميزات قاعدة المعرفة / RAG.
</details>
## 📖 استكشاف DeepTutor
ابدأ بالأسطح الرئيسية التي ستستخدمها يومياً: Chat وPartners وMy Agents وCo-Writer وBook ومركز المعرفة وفضاء التعلم والذاكرة والإعدادات. ثم تغطي الجولة عمليات النشر متعددة المستخدمين لمساحات العمل المشتركة المعزولة.
<div align="center">
<img src="../../assets/figs/web-1.4.6+/OVERVIEW.png" alt="الصفحة الرئيسية لـ DeepTutor — مساحة عمل Chat مع كل الأسطح في الشريط الجانبي" width="900">
</div>
<details>
<summary><b>🏗️ معمارية النظام</b></summary>
<div align="center">
<img src="../../assets/figs/system/system%20architecture.png" alt="معمارية نظام DeepTutor" width="900">
</div>
</details>
<details>
<summary><b>💬 Chat — حلقة الوكيل التي تستخدمها فعلاً</b></summary>
Chat هي القدرة الافتراضية والمكان الذي يبدأ فيه معظم العمل. يمكن لخيط واحد أن يتحدث عادياً، ويستدعي الأدوات، ويرتكز على قواعد المعرفة المحددة، ويقرأ المرفقات، ويولّد الصور، ويستشير الوكلاء الفرعيين، ويكتب سجلات دفتر الملاحظات، ويستمر بنفس السياق عبر الأدوار.
<div align="center">
<img src="../../assets/figs/web-1.4.6+/home/00-overview.png" alt="مساحة عمل محادثة DeepTutor" width="900">
</div>
الحلقة بسيطة عمداً: يفكر النموذج في جولات، ويستدعي الأدوات عند الحاجة، ويلاحظ النتائج، وينتهي برسالة خالية من الأدوات. `ask_user` خاص — بدلاً من التخمين، يمكن للوكيل إيقاف الدور مؤقتاً، وطرح سؤال توضيحي منظَّم، والاستئناف بمجرد إجابتك.
<div align="center">
<img src="../../assets/figs/system/chat-agent-loop.png" alt="حلقة وكيل محادثة DeepTutor" width="900">
</div>
الأدوات القابلة للتبديل من قِبَل المستخدم هي `brainstorm` و`web_search` و`paper_search` و`reason` و`geogebra_analysis` — بالإضافة إلى `imagegen` و`videogen` بمجرد تهيئة نموذج التوليد المطابق. الأدوات السياقية مثل `rag` و`read_source` و`read_memory` و`write_memory` و`read_skill` و`load_tools` و`exec` و`web_fetch` و`ask_user` و`list_notebook` و`write_note` و`github` و`consult_subagent` تُثبَّت تلقائياً عندما يكون للدور السياق الصحيح.
يأتي السياق في نوعين: **السياق اللاصق للجلسة** (الوكيل الفرعي وقواعد المعرفة والشخصية والنموذج والصوت) يعيش على شريط أدوات المؤلف ويستمر عبر الأدوار؛ **المراجع لمرة واحدة** (الملفات وتاريخ المحادثة والكتب ودفاتر الملاحظات وبنك الأسئلة والوكلاء المستوردون) تأتي من قائمة `+` لدور واحد.
Chat هي أيضاً نقطة انطلاق للقدرات الأعمق: **Quiz** لتوليد الأسئلة، و**Research** للتقارير المستشهَد بها، و**Visualize** للمخططات / الرسوم البيانية / الرسوم المتحركة، وتحت *المزيد من القدرات***Solve** للتفكير المعمق و**Mastery Path** لتدفقات خطط التعلم.
</details>
<details>
<summary><b>🤝 Partner — رفاق دائمون على نفس الدماغ</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/partners/00-partners%20overview.png" alt="مساحة عمل شركاء DeepTutor" width="900">
</div>
الشركاء هم رفاق دائمون بروحهم الخاصة وسياسة النموذج ومكتبتهم وذاكرتهم وقنواتهم. إنهم ليسوا محرك بوت منفصلاً: كل رسالة ويب أو IM واردة تصبح دوراً عادياً لـ `ChatOrchestrator` داخل مساحة عمل محدودة بنطاق الشريك. الشريك هو "محادثة لها شخصية ورقم هاتف".
<div align="center">
<img src="../../assets/figs/system/partners-architecture.png" alt="معمارية شركاء DeepTutor" width="900">
</div>
لكل شريك `SOUL.md` واختيار نموذج وقنوات وسياسة أدوات ومكتبة مخصصة. تُنسخ قواعد المعرفة والمهارات ودفاتر الملاحظات إلى `data/partners/<id>/workspace/`، لذا تعمل نفس أدوات RAG والمهارة ودفتر الملاحظات والذاكرة بدون حالات خاصة. يقرأ الشريك ذاكرة مالكه لكنه يكتب فقط في ذاكرته الخاصة.
<div align="center">
<img src="../../assets/figs/web-1.4.6+/partners/02-IM%20config%20for%20each%20partner.png" alt="إعداد قناة IM لكل شريك" width="900">
</div>
طبقة القناة مدفوعة بالمخطط ويمكنها الاتصال بمنصات IM مثل Feishu وTelegram وSlack وDiscord وDingTalk وQQ/NapCat وWeCom وWhatsApp وZulip وMattermost وMatrix وMochat وMicrosoft Teams بناءً على الإضافات المثبتة والبيانات الاعتمادية المهيأة. يمكن أيضاً توصيل الشريك كوكيل فرعي واستشارته من دور محادثة عادي — راجع **My Agents** أدناه.
</details>
<details>
<summary><b>🧑‍🚀 My Agents — استشارة واستيراد الوكلاء الآخرين</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/myagents/00-overview.png" alt="مساحة عمل My Agents في DeepTutor" width="900">
</div>
يحوّل My Agents الوكلاء الآخرين إلى سياق لـ DeepTutor، ويقوم بشيئين متمايزين. **توصيل وكيل مباشر** — Claude Code أو Codex CLI على جهازك، أو أحد شركائك — واستشارته من داخل دور محادثة: DeepTutor *يشغّل* الوكيل الآخر فعلاً ويبث عمله إلى لوحة Activity عبر أداة `consult_subagent`. اختره بشريحة الوكيل (أو اكتب `@`)، وحدد عدد الجولات التي يمكن للاستشارة أن تأخذها.
<div align="center">
<img src="../../assets/figs/web-1.4.6+/home/08-subagent%20demo%20with%20claude%20code.png" alt="استشارة وكيل Claude Code الفرعي مباشرةً" width="900">
</div>
**استيراد المحادثات السابقة** — أحضر تاريخ Claude Code وCodex الموجود لديك كوكلاء مسماة قابلة للبحث والاستئناف. اختر الأيام التي تريد استيرادها؛ التحديث يعيد مزامنتها. استشر محادثة مستوردة من أي دور محادثة عبر `+` ← My Agents، وسيقرأها DeepTutor كنصوص محادثة لطرف ثالث — تبقى *محادثتهم*، وليس صوت DeepTutor الخاص.
</details>
<details>
<summary><b>✍️ Co-Writer — صياغة Markdown واعية بالتحديد</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/co-writer/00-overview.png" alt="مساحة عمل Co-Writer في DeepTutor" width="900">
</div>
Co-Writer هو مساحة عمل Markdown ذات عرض مقسَّم للتقارير والدروس التعليمية والملاحظات والقطع التعليمية الطويلة. تحفظ المستندات تلقائياً وتُظهر معاينة مباشرة (رياضيات KaTeX وأسوار الرسم البياني)، ويمكن حفظها مرة أخرى في دفاتر الملاحظات عندما تصبح المسودة سياقاً قابلاً لإعادة الاستخدام.
<div align="center">
<img src="../../assets/figs/web-1.4.6+/co-writer/01-edit%20panel.png" alt="محرر Co-Writer مع معاينة مباشرة" width="900">
</div>
الفكرة المحورية هي **التحرير الجراحي**: حدد نطاقاً واطلب من DeepTutor إعادة كتابته أو توسيعه أو تقصيره. يمكن لوكيل التحرير ترسيخ التغيير في قاعدة معرفة أو دليل ويب، ويحتفظ بآثار استدعاءات أدواته، ويعرض كل تغيير كـ diff قبول/رفض — لذا لا شيء يُقبَل حتى توافق عليه.
</details>
<details>
<summary><b>📖 Book — كتب حية من موادك</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/book/00-book_overview.png" alt="مكتبة كتب DeepTutor" width="900">
</div>
يحوّل Book المصادر المحددة إلى **كتاب حي** تفاعلي — ليس PDF ثابتاً، بل بيئة قراءة مبنية من كتل مكتوبة. يمكن أن يبدأ الكتاب من قواعد المعرفة أو دفاتر الملاحظات أو بنوك الأسئلة أو تاريخ المحادثة؛ يقترح تدفق الإنشاء هيكل فصل قبل توليد المحتوى، لذا تراجع الشكل بدلاً من قبول مخرجات عشوائية.
<p align="center">
<img src="../../assets/figs/web-1.4.6+/book/01-book-demo-quiz%20card.png" alt="كتلة اختبار في الكتاب" width="31%">
&nbsp;
<img src="../../assets/figs/web-1.4.6+/book/02-book-demo-manim%20video.png" alt="كتلة رسوم متحركة Manim في الكتاب" width="31%">
&nbsp;
<img src="../../assets/figs/web-1.4.6+/book/03-book-demo%20interactive%20module.png" alt="كتلة ودجت تفاعلية في الكتاب" width="31%">
</p>
يُجمِّع كل فصل إلى كتل مكتوبة — نصوص وأقسام وتنبيهات واختبارات وبطاقات فلاش وجداول زمنية ورمز وأشكال وHTML تفاعلية ورسوم متحركة وأشكال مفاهيم وغوص عميق وملاحظات مستخدم — وكل صفحة لها Page Chat الخاصة بها. الكتل قابلة للتحرير: أدرج أو حرّك أو أعد التوليد أو غيّر نوع الكتلة بدون إعادة كتابة الفصل. أوامر الصيانة مثل `deeptutor book health` و`deeptutor book refresh-fingerprints` تساعد في الكشف عن انجراف معرفة المصدر من الصفحات المُجمَّعة.
</details>
<details>
<summary><b>📚 مركز المعرفة — مكتبات RAG متعددة المحركات</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/knowledge/00-overview.png" alt="مركز المعرفة في DeepTutor" width="900">
</div>
قواعد المعرفة هي مجموعات المستندات وراء RAG — إنها ترسّخ أدوار Chat وتحرير Co-Writer وتوليد Book ومحادثات Partner. ما يميزها هو **اختيار محرك الاسترجاع**: **LlamaIndex** (الافتراضي، ناقل محلي + BM25)، **PageIndex** (مستضاف، استرجاع تفكيري مع استشهادات على مستوى الصفحة)، **GraphRAG** و**LightRAG** (استرجاع قائم على الرسم البياني المعرفي)، **LightRAG Server** (استرجاع مُحال إلى نسخة LightRAG خارجية تتصل بها عبر HTTP)، أو مخزن **Obsidian** مرتبط يقرأ المدرس ويكتب فيه في مكانه. كل قاعدة معرفة مرتبطة بمحرك واحد.
<div align="center">
<img src="../../assets/figs/web-1.4.6+/knowledge/01-create%20knowledge%20base.png" alt="إنشاء قاعدة معرفة" width="900">
</div>
عند إنشاء قاعدة معرفة، إما أن **تنشئ جديدة** (تحميل مستندات وبناء فهرس جديد) أو **تربط موجودة** (إعادة استخدام فهرس مبني في مكان آخر، قراءة في مكانه بدون إعادة فهرسة). تكتب إعادة الفهرسة دليل `version-N` مسطحاً جديداً وتحتفظ بالسابقة، لذا لا يُدمَّر فهرس عامل أبداً أثناء إعادة البناء. يمكن إزالة مستند واحد حتى من قاعدة في حالة **خطأ** — إسقاط ملف فشل تحليله بدون حذف وإعادة بناء كاملين. تحليل المستندات — نص فقط أو MinerU أو Docling أو markitdown أو PyMuPDF4LLM — يُختار في **الإعدادات ← قاعدة المعرفة**، مع إيقاف تنزيلات النماذج المحلية افتراضياً. تعكس واجهة CLI دورة الحياة مع `deeptutor kb list` و`info` و`create` و`add` و`search` و`set-default` و`delete`.
</details>
<details>
<summary><b>🌐 فضاء التعلم — المهارات والشخصيات والسياق القابل لإعادة الاستخدام</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/learning-space/00-overview.png" alt="مركز فضاء التعلم في DeepTutor" width="900">
</div>
فضاء التعلم هو طبقة المكتبة والتخصيص — حيث تعيش الأشياء التي تستمر. **المحادثات والمواد** تحتفظ بتاريخ المحادثة ودفاتر الملاحظات وبنك الأسئلة (كل سؤال محفوظ يحتفظ بإجابتك والإجابة المرجعية وشرحاً). **التخصيص** يحتفظ بمسارات الإتقان والشخصيات (إعدادات السلوك المسبقة مثل *زميل* و*مساعد بحثي* و*معلم*) والمهارات (دليل `SKILL.md` يقرأه النموذج عند الطلب). كل شيء هنا يمكن إعادة استخدامه من Chat وPartners وCo-Writer وBook.
<div align="center">
<img src="../../assets/figs/web-1.4.6+/learning-space/07-%20download%20skills%20from%20eduhub.png" alt="استيراد مهارات من EduHub" width="900">
</div>
لا يجب عليك كتابة كل مهارة بنفسك — **الاستيراد من EduHub** يتصفح الكتالوج المجتمعي ويُنزّل المهارة مباشرةً إلى مكتبتك من خلال بوابة أمان (راجع [النظام البيئي](#-النظام-البيئي--eduhub-ومجتمع-المهارات)).
</details>
<details>
<summary><b>🧠 Memory — تخصيص قابل للتدقيق</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/memory/00-overview.png" alt="نظرة عامة على ذاكرة DeepTutor" width="900">
</div>
الذاكرة نظام ثلاثي الطبقات مدعوم بالملفات يمكنك قراءته وتنظيمه ومراجعته — وهو عمداً *ليس* مخزناً ناقلاً مخفياً. **L1** هو مرآة مساحة العمل بالإضافة إلى آثار أحداث تراكمية فقط (`trace/<surface>/<date>.jsonl`**L2** هو حقائق منظَّمة لكل سطح (`L2/<surface>.md`**L3** هو تركيب عبر الأسطح (`L3/<profile|recent|scope|preferences>.md`). لأن L2 يستشهد بـ L1 وL3 يستشهد بـ L2، لا شيء في ملفك الشخصي غير مسؤول.
<div align="center">
<img src="../../assets/figs/web-1.4.6+/memory/01-3%20layer%20memory%20graph.png" alt="رسم بياني لذاكرة DeepTutor" width="900">
</div>
يُظهر Memory Graph الهرم بأكمله — تركيب L3 في المركز وL2 في الحلقة الوسطى وآثار L1 في الخارج — لذا يمكنك تتبع أي ادعاء مُوليَّف إلى الحدث الخام الدقيق خلفه. يُتتبع الذاكرة عبر أسطح `chat` و`notebook` و`quiz` و`kb` و`book` والشريك و`cowriter`؛ ميزانيات تحديث الموحّد / تدقيقه / إلغاء تكراره تُضبط في **الإعدادات ← الذاكرة**.
</details>
<details>
<summary><b>⚙️ الإعدادات — لوحة تحكم واحدة</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/settings/00-setting%20overview.png" alt="مركز إعدادات DeepTutor" width="900">
</div>
الإعدادات هي لوحة التحكم التشغيلية، مع شريط حالة مباشر (الخلفية وLLM والتضمين والبحث) وبطاقة واحدة لكل منطقة: **المظهر** (الثيمة + لغة واجهة المستخدم)، **الشبكة** (قاعدة API والمنافذ وCORS)، **النماذج** (LLM والتضمين والبحث وتحويل النص إلى كلام وتحويل الكلام إلى نص وتوليد الصور وتوليد الفيديو)، **قاعدة المعرفة** (محرك تحليل المستندات)، **Chat** (الأدوات وخوادم MCP والمعاملات لكل قدرة)، **الشركاء والوكلاء** (الوكلاء الفرعيون الذين يمكنك استشارتهم من دور)، و**الذاكرة** (ميزانيات الموحّد).
<div align="center">
<img src="../../assets/figs/web-1.4.6+/settings/01-appearance%20settings.png" alt="إعدادات المظهر والثيمات في DeepTutor" width="900">
</div>
تستخدم معظم الأقسام تدفق صياغة-وتطبيق، لذا يمكنك اختبار مزود قبل الالتزام به. تشحن أربع ثيمات في الصندوق — Default وCream وDark وGlass. ملفات `.env` في جذر المشروع تُتجاهل عمداً؛ يعيش تهيئة وقت التشغيل تحت `data/user/settings/*.json` إلا إذا وجّه `DEEPTUTOR_HOME` أو `deeptutor start --home` التطبيق في مكان آخر.
</details>
<details>
<summary><b>👥 متعدد المستخدمين — النشر المشترك</b> · مصادقة اختيارية، مساحات عمل معزولة لكل مستخدم</summary>
المصادقة **معطلة افتراضياً** — يعمل DeepTutor لمستخدم واحد. فعّلها وشجرة `data/` واحدة تستضيف مساحة عمل المشرف ومساحات عمل معزولة لكل مستخدم ومساحات عمل الشريك جنباً إلى جنب:
```text
data/
├── user/ # مساحة عمل المشرف + الإعدادات العامة
├── users/<uid>/ # نطاق المستخدم: تاريخ المحادثة والذاكرة ودفاتر الملاحظات وقواعد المعرفة
├── partners/<id>/workspace/ # نطاق المستخدم الاصطناعي (الشريك)
└── system/ # auth/users.json · grants/<uid>.json · audit/usage.jsonl
```
**أول مستخدم مسجَّل يصبح مشرفاً** ويمتلك كتالوجات النماذج وبيانات اعتماد المزود وقواعد المعرفة المشتركة والمهارات والمنح لكل مستخدم. يحصل الجميع الآخرون على مساحة عمل معزولة وصفحة إعدادات منقوصة — تظهر النماذج وقواعد المعرفة والمهارات المعيّنة من المشرف كخيارات محدودة النطاق وللقراءة فقط، وليس كمفاتيح API خام.
**تفعيله:** فعّل المصادقة في `data/user/settings/auth.json`، وأعد تشغيل `deeptutor start`، وسجّل أول مشرف على `/register`، ثم أضف المستخدمين من `/admin/users` وعيّن النماذج وقواعد المعرفة والمهارات والـ Partners وسياسة الأداة/MCP ووصول تنفيذ الرمز من خلال المنح.
> يبقى PocketBase تكاملاً لمستخدم واحد — أبقِ `integrations.pocketbase_url` فارغاً لعمليات النشر متعددة المستخدمين إلا إذا وصلت مخزن مستخدم خارجي.
</details>
## ⌨️ واجهة سطر أوامر DeepTutor — الواجهة الأصيلة للوكلاء
ثنائي `deeptutor` واحد، طريقتان للدخول: **REPL** تفاعلي للأشخاص الذين يعيشون في الطرفية، و**JSON** منظَّم للوكلاء الأخرى التي تقود DeepTutor كأداة. نفس القدرات والأدوات وقواعد المعرفة في كلتا الحالتين.
<details>
<summary><b>قدّها بنفسك</b></summary>
`deeptutor chat` يفتح REPL تفاعلياً؛ `deeptutor run <capability> "<message>"` يُشغّل دوراً واحداً ويخرج. يتحدث كلاهما بنفس علامات `--capability` و`--tool` و`--kb` و`--config`.
```bash
deeptutor chat # REPL تفاعلي
deeptutor chat --capability deep_solve --kb my-kb --tool rag
deeptutor run chat "Explain the Fourier transform" --tool rag --kb textbook
deeptutor run deep_research "Survey 2026 papers on RAG" \
--config mode=report --config depth=standard
```
كل ما يفعله تطبيق الويب موجود هنا أيضاً — قواعد المعرفة (`kb`)، والجلسات (`session`)، والشركاء (`partner`)، والمهارات (`skill`)، ودفاتر الملاحظات، والذاكرة، والتهيئة. القائمة الكاملة أدناه.
</details>
<details>
<summary><b>دع وكيلاً يقودها</b></summary>
DeepTutor مبنية لتكون *مُشغَّلة بواسطة وكيل آخر*. أضف `--format json` إلى أي `run` وكل دور يبث **NDJSON — حدث واحد في كل سطر** (`content` و`tool_call` و`tool_result` و`done` و...)، وكل سطر مُعنوَن بـ `session_id` الخاص به. التشغيلات آمنة بدون TTY: توقف `ask_user` بدون TTY يحل تلقائياً برد فارغ بدلاً من التعليق.
```bash
# لقطة واحدة، قابلة للقراءة آلياً
deeptutor run deep_solve "Find d/dx[sin(x^2)]" --tool reason --format json
# سلسل الأدوار في جلسة واحدة ذات حالة — التقط المعرّف، أعد استخدامه
SID=$(deeptutor run deep_research "Survey 2026 papers on RAG" \
--config mode=report --config depth=standard --format json \
| jq -r 'select(.type=="done").session_id')
deeptutor run deep_question "Quiz me on that survey" --session "$SID" --format json
```
يشحن المستودع بملف [`SKILL.md`](../../SKILL.md) في الجذر — وثيقة تسليم بنحو 150 سطراً تعلّم أي LLM يستخدم الأدوات السطح بأكمله في قراءة واحدة. سلّمها إلى Claude Code أو Codex أو OpenCode (يلتقطون `SKILL.md` تلقائياً)، أو لفّ `deeptutor run` كأداة في حلقة LangChain / AutoGen. الوصفات الكاملة: [Agent Handoff](https://deeptutor.info/docs/cli/agent-handoff/).
</details>
<details>
<summary><b>مرجع الأوامر</b></summary>
| الأمر | الوصف |
|:---|:---|
| `deeptutor init` | إنشاء أو تحديث `data/user/settings` لمساحة العمل الحالية |
| `deeptutor start [--home PATH]` | تشغيل الخلفية + الواجهة الأمامية معاً |
| `deeptutor serve [--port PORT]` | تشغيل خلفية FastAPI فقط |
| `deeptutor run <capability> <message>` | تشغيل دور قدرة واحدة (`chat` و`deep_solve` و`deep_question` و`deep_research` و`visualize` و`math_animator` و`mastery_path`)؛ أضف `--format json` لإخراج NDJSON |
| `deeptutor chat` | REPL تفاعلي مع تحكمات القدرة والأداة وقاعدة المعرفة ودفتر الملاحظات والتاريخ |
| `deeptutor partner list/create/start/stop` | إدارة الشركاء المتصلين بـ IM |
| `deeptutor kb list/info/create/add/search/set-default/delete` | إدارة قواعد المعرفة LlamaIndex |
| `deeptutor skill search/install/list/remove/login/logout/publish/update` | إدارة المهارات، التثبيت من المراكز، ونشر مهاراتك الخاصة (`eduhub:<slug>` افتراضياً، راجع النظام البيئي) |
| `deeptutor memory show/clear` | فحص مستندات الذاكرة L2/L3 أو مسح ذاكرة L1/الكل |
| `deeptutor session list/show/open/rename/delete` | إدارة الجلسات المشتركة |
| `deeptutor notebook list/create/show/add-md/replace-md/remove-record` | إدارة دفاتر الملاحظات من ملفات Markdown |
| `deeptutor book list/health/refresh-fingerprints` | فحص الكتب وتحديث بصمات المصادر |
| `deeptutor plugin list/info` | فحص الأدوات والقدرات المسجلة |
| `deeptutor config show` | طباعة ملخص التهيئة |
| `deeptutor provider login <provider>` | مصادقة المزود (`openai-codex` OAuth login؛ `github-copilot` يتحقق من جلسة مصادقة Copilot موجودة) |
</details>
<details>
<summary><b>توزيع CLI فقط</b></summary>
حزمة CLI فقط تعيش في `packaging/deeptutor-cli`. في هذه النسخة، ثبّتها من المصدر:
```bash
python -m pip install -e ./packaging/deeptutor-cli
```
لم تُنشر على PyPI بعد، لذا يحتفظ قسم [البدء](#-البدء) الرئيسي بمسار التثبيت من المصدر.
</details>
## 🧩 النظام البيئي — EduHub ومجتمع المهارات
تستخدم مهارات DeepTutor تنسيق **Agent-Skills** المفتوح — مجلد يحتوي دليل `SKILL.md` (YAML frontmatter + Markdown) وملفات مرجعية اختيارية. لا شيء في ذلك خاص بـ DeepTutor، لذا أي سجل يتحدث التنسيق يصبح مصدراً لمكتبتك. يشحن DeepTutor مع **[EduHub](https://eduhub.deeptutor.info/)** — سجل المهارات المركّز على التعليم الخاص بنا — مُوصَّلاً كمركز افتراضي.
<details>
<summary><b>EduHub — النظام البيئي للمهارات في DeepTutor</b></summary>
[**EduHub**](https://eduhub.deeptutor.info/) هو المركز المجتمعي الذي أطلقه DeepTutor لمشاركة مهارات الوكيل الموجهة نحو التعليم — موجهو سقراط وبناة بطاقات الفلاش وتغذية راجعة للمقالات وخطط الامتحانات وشارحو المفاهيم وغيرها. مُدمَج في DeepTutor، لذا لا شيء يجب تهيئته: slug مجرد أو بادئة `eduhub:` تحل إليه.
**البحث والتثبيت** — في المتصفح، افتح **فضاء التعلم ← المهارات ← الاستيراد من EduHub** لتصفح الكتالوج وتنزيل مهارة مباشرةً إلى مكتبتك. من الطرفية:
```bash
deeptutor skill search "socratic tutor" # البحث في EduHub (المركز الافتراضي)
deeptutor skill install socratic-tutor # جلب → التحقق → التسجيل
deeptutor skill install eduhub:socratic-tutor@1.2.0 # تثبيت مركز وإصدار محددين
deeptutor skill list # المهارات المحلية مع مصدرها من المركز
```
**انشر مهارتك الخاصة** — حزّم `SKILL.md` وشاركها مع المجتمع:
```bash
deeptutor skill login # تسجيل دخول المتصفح إلى EduHub
deeptutor skill publish ./my-skill # تفاعلي: اختر track + tags، ثم رفع
deeptutor skill update # تراجع أو أصدر إصداراً جديداً
```
EduHub هو أيضاً سجل مستقل متوافق مع ClawHub، لذا الوكلاء الذين ليسوا DeepTutor (Claude Code وCodex و...) يمكنهم استخدامه مباشرةً من خلال واجهة `eduhub``npx eduhub install socratic-tutor`.
</details>
<details>
<summary><b>بوابة أمان الاستيراد</b></summary>
مهما كان المصدر، كل استيراد يمر من **نفس بوابة الأمان** قبل أن يلمس أي شيء مساحة عملك:
- يُفحَص **حكم الأمان** للسجل أولاً — الحزم الموسومة ترفض إلا إذا مررت `--allow-unverified`؛
- تُستخرَج الأرشيفات بشكل دفاعي (حراس zip-slip / zip-bomb) خلف **قائمة بيضاء للاحقات** نص/نص، لذا الثنائيات لا تصل أبداً إلى مساحة العمل؛
- تُعيَّر الـ frontmatter إلى مخطط DeepTutor و`always:` **تُزال**، لذا مهارة محملة لا يمكنها أبداً إجبار نفسها في كل مطالبة نظام؛
- المصدر — المركز والإصدار والحكم ووقت التثبيت — يُكتب إلى `.hub-lock.json` للمراجعات والتحديثات.
في عمليات النشر متعددة المستخدمين، التثبيت للمشرفين فقط: تهبط مهارة جديدة في كتالوج المشرف وتظل غير مرئية للمستخدمين الآخرين حتى تعيّنها منحة، لذا يمكن للمشرف فحصها قبل طرحها.
</details>
<details>
<summary><b>متوافق أيضاً مع ClawHub</b></summary>
لأن DeepTutor يتحدث تنسيق Agent-Skills المفتوح، **[ClawHub](https://clawhub.ai/)** يعمل كمصدر من الدرجة الأولى أيضاً — مُدمَج جنباً إلى جنب مع EduHub. اختره ببادئة المركز:
```bash
deeptutor skill search "git release notes" --hub clawhub
deeptutor skill install clawhub:git-release-notes@1.0.1
```
أضف المزيد من السجلات في `settings/skill_hubs.json`: إدخال `type: "clawhub"` يشير إلى أي HTTP API متوافق (EduHub وClawHub يتحدثانه كلاهما)، `type: "command"` يلفّ أي CLI جلب يشحنه السجل، و`"default"` يختار المركز المستخدم للـ slugs المجردة. كلها تُغذّي نفس بوابة الاستيراد.
</details>
## 🌐 المجتمع
### 📮 التواصل
DeepTutor هو مشروع مفتوح المصدر تقوده [Bingxi Zhao](https://github.com/pancacake) ضمن مجموعة [HKUDS](https://github.com/HKUDS)، ويتطور بشكل **مفتوح المصدر بالكامل**، مبني مع المجتمع. حتى الآن، **لا يوجد** لدينا أي منتجات مدفوعة عبر الإنترنت من أي شكل. تفضّل بالتواصل على **bingxizhao39@gmail.com** للنقاشات والأفكار والتعاون.
### 🙏 التقدير
خالص الشكر لـ [**Chao Huang**](https://sites.google.com/view/chaoh)، مدير مختبر ذكاء البيانات @ HKU، ولزملائنا في HKUDS على دعمهم الحار — وخاصةً [**Jiahao Zhang**](https://github.com/zzhtx258)، و[**Zirui Guo**](https://github.com/LarFii)، و[**Xubin Ren**](https://github.com/Re-bin). ونحن ممتنون عميقاً أيضاً لـ **مجتمع المصادر المفتوحة**: نجومكم وإصداراتكم وطلبات السحب والنقاشات تشكّل DeepTutor كل يوم.
يقف DeepTutor أيضاً على أكتاف مشاريع مفتوحة المصدر متميزة أعطتنا أدوات وإلهاماً:
| المشروع | الدور / الإلهام |
|:---|:---|
| [**LlamaIndex**](https://github.com/run-llama/llama_index) | العمود الفقري لخط أنابيب RAG وفهرسة المستندات |
| [**nanobot**](https://github.com/HKUDS/nanobot) | محرك وكيل خفيف الوزن للغاية مكّن TutorBot الأصلي *(HKUDS)* |
| [**LightRAG**](https://github.com/HKUDS/LightRAG) | RAG بسيط وسريع *(HKUDS)* |
| [**AutoAgent**](https://github.com/HKUDS/AutoAgent) | إطار وكيل بدون رمز *(HKUDS)* |
| [**AI-Researcher**](https://github.com/HKUDS/AI-Researcher) | خط أنابيب بحث آلي *(HKUDS)* |
| [**OpenClaw**](https://github.com/openclaw/openclaw) | بوابة وكيل مفتوحة ونظام مهارات وراء ClawHub |
| [**Codex**](https://github.com/openai/codex) | واجهة برمجة أصيلة للوكلاء ألهمت سير عمل CLI لدينا |
| [**Claude Code**](https://github.com/anthropics/claude-code) | واجهة برمجة للوكلاء ألهمت حلقة وكيل DeepTutor |
| [**ManimCat**](https://github.com/Wing900/ManimCat) | توليد رسوم متحركة رياضية مدفوع بالذكاء الاصطناعي لـ Math Animator |
### 🗺️ خارطة الطريق والمساهمة
نريد لـ DeepTutor أن يستمر في التطور والتحسين — وفي نهاية المطاف أن يصبح هدية نقدمها للمجتمع مفتوح المصدر. يُحدَّث [**خارطة طريقنا**](https://github.com/HKUDS/DeepTutor/issues/498) باستمرار؛ صوّت على العناصر هناك أو اقترح عناصر جديدة. إذا كنت ترغب في المساهمة، راجع [**دليل المساهمة**](../../CONTRIBUTING.md) لمعرفة استراتيجية الفروع ومعايير البرمجة وكيفية البدء.
<div align="center">
نأمل أن يصبح DeepTutor هدية للمجتمع. 🎁
<a href="https://github.com/HKUDS/DeepTutor/graphs/contributors">
<img src="https://contrib.rocks/image?repo=HKUDS/DeepTutor&max=999" alt="المساهمون" />
</a>
</div>
<div align="center">
<a href="https://www.star-history.com/#HKUDS/DeepTutor&type=timeline&legend=top-left">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=HKUDS/DeepTutor&type=timeline&theme=dark&legend=top-left" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=HKUDS/DeepTutor&type=timeline&legend=top-left" />
<img alt="مخطط تاريخ النجوم" src="https://api.star-history.com/svg?repos=HKUDS/DeepTutor&type=timeline&legend=top-left" />
</picture>
</a>
</div>
<p align="center">
<a href="https://www.star-history.com/hkuds/deeptutor">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/badge?repo=HKUDS/DeepTutor&theme=dark" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/badge?repo=HKUDS/DeepTutor" />
<img alt="ترتيب تاريخ النجوم" src="https://api.star-history.com/badge?repo=HKUDS/DeepTutor" />
</picture>
</a>
</p>
<div align="center">
مرخّص بموجب [رخصة Apache 2.0](../../LICENSE).
<p>
<img src="https://visitor-badge.laobi.icu/badge?page_id=HKUDS.DeepTutor&style=for-the-badge&color=00d4ff" alt="المشاهدات">
</p>
</div>
+707
View File
@@ -0,0 +1,707 @@
<div align="center">
<p align="center"><img src="../../assets/figs/logo/logo.png" alt="DeepTutor logo" height="56" style="vertical-align: middle;">&nbsp;<img src="../../assets/figs/logo/banner.png" alt="DeepTutor" height="48" style="vertical-align: middle;"></p>
# DeepTutor:终身个性化辅导
<p align="center">
<a href="https://deeptutor.info" target="_blank"><img alt="Docs — deeptutor.info" src="https://img.shields.io/badge/Docs-deeptutor.info%20%E2%86%97-0A0A0A?style=for-the-badge&labelColor=F5F5F4" height="36"></a>
</p>
<p align="center">
<a href="https://trendshift.io/repositories/17099?utm_source=repository-badge&amp;utm_medium=badge&amp;utm_campaign=badge-repository-17099" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/repositories/17099" alt="HKUDS%2FDeepTutor | Trendshift" width="250" height="55"/></a>&nbsp;
<a href="https://trendshift.io/repositories/17099?utm_source=trendshift-badge&amp;utm_medium=badge&amp;utm_campaign=badge-trendshift-17099" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/17099/daily" alt="HKUDS%2FDeepTutor | Trendshift" width="250" height="55"/></a>&nbsp;
<a href="https://trendshift.io/repositories/17099?utm_source=trendshift-badge&amp;utm_medium=badge&amp;utm_campaign=badge-trendshift-17099" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/17099/weekly?language=Python" alt="HKUDS%2FDeepTutor | Trendshift" width="250" height="55"/></a>
</p>
<p align="center">
<a href="../../README.md"><img alt="English" height="40" src="https://img.shields.io/badge/English-CDCFD4"></a>&nbsp;
<a href="README_CN.md"><img alt="简体中文" height="40" src="https://img.shields.io/badge/简体中文-BCDCF7"></a>&nbsp;
<a href="README_JA.md"><img alt="日本語" height="40" src="https://img.shields.io/badge/日本語-CDCFD4"></a>&nbsp;
<a href="README_ES.md"><img alt="Español" height="40" src="https://img.shields.io/badge/Español-CDCFD4"></a>&nbsp;
<a href="README_FR.md"><img alt="Français" height="40" src="https://img.shields.io/badge/Français-CDCFD4"></a>&nbsp;
<a href="README_AR.md"><img alt="Arabic" height="40" src="https://img.shields.io/badge/Arabic-CDCFD4"></a>&nbsp;
<a href="README_RU.md"><img alt="Русский" height="40" src="https://img.shields.io/badge/Русский-CDCFD4"></a>&nbsp;
<a href="README_HI.md"><img alt="Hindi" height="40" src="https://img.shields.io/badge/Hindi-CDCFD4"></a>&nbsp;
<a href="README_PT.md"><img alt="Português" height="40" src="https://img.shields.io/badge/Português-CDCFD4"></a>&nbsp;
<a href="README_TH.md"><img alt="Thai" height="40" src="https://img.shields.io/badge/Thai-CDCFD4"></a>&nbsp;
<a href="README_PL.md"><img alt="Polski" height="40" src="https://img.shields.io/badge/Polski-CDCFD4"></a>
</p>
[![Python 3.11+](https://img.shields.io/badge/Python-3.11%2B-3776AB?style=flat-square&logo=python&logoColor=white)](https://www.python.org/downloads/)
[![Next.js 16](https://img.shields.io/badge/Next.js-16-000000?style=flat-square&logo=next.js&logoColor=white)](https://nextjs.org/)
[![License](https://img.shields.io/badge/License-Apache_2.0-blue?style=flat-square)](LICENSE)
[![GitHub release](https://img.shields.io/github/v/release/HKUDS/DeepTutor?style=flat-square&color=brightgreen)](https://github.com/HKUDS/DeepTutor/releases)
[![arXiv](https://img.shields.io/badge/arXiv-2604.26962-b31b1b?style=flat-square&logo=arxiv&logoColor=white)](https://arxiv.org/abs/2604.26962)
[![Discord](https://img.shields.io/badge/Discord-社区-5865F2?style=flat-square&logo=discord&logoColor=white)](https://discord.gg/eRsjPgMU4t)
[![Feishu](https://img.shields.io/badge/飞书-交流群-00D4AA?style=flat-square&logo=feishu&logoColor=white)](./Communication.md)
[![WeChat](https://img.shields.io/badge/微信-交流群-07C160?style=flat-square&logo=wechat&logoColor=white)](https://github.com/HKUDS/DeepTutor/issues/78)
[核心功能](#-核心功能) · [快速开始](#-快速开始) · [功能探索](#-探索-deeptutor) · [CLI 命令行](#-deeptutor-cli--智能体原生界面) · [生态系统](#-生态系统--eduhub-与技能社区) · [社区](#-社区)
</div>
---
> 🤝 **欢迎各种形式的贡献!** 在 [`路线图`](https://github.com/HKUDS/DeepTutor/issues/498) 为议题投票或提出新建议,详见 [贡献指南](CONTRIBUTING.md),了解分支策略、编码规范及参与方式。
### 📰 新闻动态
- **2026-05-22** 🌐 官方文档站点上线 [**deeptutor.info**](https://deeptutor.info/) — 指南、参考文档与能力演示一站汇聚。
- **2026-04-19** 🎉 111 天突破 2 万 Star!感谢大家对真正个性化智能辅导的支持。
- **2026-04-10** 📄 论文已发布于 arXiv — 阅读 [预印本](https://arxiv.org/abs/2604.26962),了解 DeepTutor 的设计理念与背后的思考。
- **2026-02-06** 🚀 仅 39 天突破 1 万 Star!衷心感谢我们出色的社区。
- **2026-01-01** 🎊 新年快乐!加入我们的 [Discord](https://discord.gg/eRsjPgMU4t)、[微信群](https://github.com/HKUDS/DeepTutor/issues/78) 或 [Discussions](https://github.com/HKUDS/DeepTutor/discussions) — 一起塑造 DeepTutor 的未来。
- **2025-12-29** 🎓 DeepTutor 正式发布!
## ✨ 核心功能
DeepTutor 是一个智能体原生的学习工作区,将辅导、解题、测验生成、研究、可视化和掌握度练习整合在一个可扩展的系统中。
- **统一的运行时** — Chat、Quiz、Research、Visualize、Solve 和 Mastery Path 运行在同一个智能体循环上,切换的是目标,而非引擎,上下文始终随学习者流转。
- **互联的学习上下文** — 知识库、书籍、Co-Writer 草稿、笔记本、题库、人格预设和 Memory,在每个工作流中始终可用,而不是各自孤立。
- **子智能体与 Partners** — 在任意对话轮次中调用实时运行的 Claude Code、Codex 或 Partner(或导入其历史对话),并在同一大脑上运行持久化的 IM 伴侣。
- **多引擎知识库** — 跨 LlamaIndex、PageIndex、GraphRAG、LightRAG 或链接的 Obsidian vault 的版本化 RAG 知识库,支持可插拔的文档解析。
- **可扩展工具与技能** — 内置工具、MCP 服务器、图像 / 视频 / 语音生成模型,以及从 EduHub 安装的社区技能。
- **可审计的记忆** — L1 追踪、L2 表面摘要和 L3 综合让个性化透明可编辑,Memory Graph 将每一条结论追溯到其原始证据。
---
## 🚀 快速开始
DeepTutor 提供四种安装方式,共享同一个工作区布局:设置存储在启动目录下的 `data/user/settings/`(或通过 `DEEPTUTOR_HOME` / `deeptutor start --home` 指定的位置)。完整应用的推荐流程为:**选择工作目录 → 安装 → `deeptutor init``deeptutor start`**。
<details>
<summary><b>方式一 — 从 PyPI 安装</b> · 完整本地 Web 应用 + CLI,无需克隆仓库</summary>
完整本地 Web 应用 + CLI,无需克隆仓库。需要 **Python 3.11+** 以及 PATH 中的 **Node.js 20+** 运行时(打包的 Next.js 独立服务器由 `deeptutor start` 启动)。
```bash
mkdir -p my-deeptutor && cd my-deeptutor
pip install -U deeptutor
deeptutor init # 提示配置端口 + LLM 提供商 + 可选嵌入
deeptutor start # 启动后端 + 前端;保持终端窗口打开
```
`deeptutor init` 会提示配置后端端口(默认 `8001`)、前端端口(默认 `3782`)、LLM 提供商 / 基础 URL / API Key / 模型,以及可选的知识库 / RAG 嵌入提供商。
`deeptutor start` 完成后,打开终端打印的前端 URL — 默认为 [http://127.0.0.1:3782](http://127.0.0.1:3782)。在该终端按 `Ctrl+C` 可同时停止后端和前端。跳过 `deeptutor init` 也可用于快速体验;应用会以默认端口和空模型设置启动,稍后在 **Settings → Models** 中配置即可。
</details>
<details>
<summary><b>方式二 — 从源码安装</b> · 基于代码仓库进行开发</summary>
适用于基于代码仓库的开发。使用 **Python 3.11+****Node.js 22 LTS** 以匹配 CI 和 Docker 环境。
```bash
git clone https://github.com/HKUDS/DeepTutor.git
cd DeepTutor
# 创建 venvmacOS/Linux)。Windows PowerShell
# py -3.11 -m venv .venv ; .\.venv\Scripts\Activate.ps1
python3 -m venv .venv && source .venv/bin/activate
python -m pip install --upgrade pip
# 安装后端 + 前端依赖
python -m pip install -e .
( cd web && npm ci --legacy-peer-deps )
deeptutor init
deeptutor start
```
源码安装会以开发模式运行 Next.js,指向本地 `web/` 目录;其他所有内容(配置布局、端口、`Ctrl+C` 停止)与方式一相同。
<details>
<summary><b>Conda 环境</b>(替代 <code>venv</code></summary>
```bash
conda create -n deeptutor python=3.11
conda activate deeptutor
python -m pip install --upgrade pip
```
</details>
<details>
<summary><b>可选安装额外依赖</b> — dev / partners / matrix / math-animator</summary>
```bash
pip install -e ".[dev]" # 测试/代码检查工具
pip install -e ".[partners]" # Partner IM 渠道 SDK + MCP 客户端
pip install -e ".[matrix]" # Matrix 渠道(不含 E2EE/libolm
pip install -e ".[matrix-e2e]" # Matrix E2EE;需要 libolm
pip install -e ".[math-animator]" # Manim 插件;需要 LaTeX/ffmpeg/系统库
```
</details>
<details>
<summary><b>前端依赖调整与开发服务器故障排查</b></summary>
**修改前端依赖:** 运行 `npm install --legacy-peer-deps` 以刷新 `web/package-lock.json`,然后同时提交 `web/package.json``web/package-lock.json`
**开发服务器卡住:** 如果 `deeptutor start` 报告有已存在但无响应的前端进程,停止它打印的 PID。如果实际上没有 Next.js 进程在运行,则锁文件已过时 — 删除后重试:
```bash
rm -f web/.next/dev/lock web/.next/lock
deeptutor start
```
</details>
</details>
<details>
<summary><b>方式三 — Docker</b> · 单一自包含容器</summary>
单容器运行完整 Web 应用。镜像托管在 GitHub Container Registry
- `ghcr.io/hkuds/deeptutor:latest` — 稳定版本
- `ghcr.io/hkuds/deeptutor:pre` — 预发布版本(如有)
> 有关 podman / 无根容器 / 只读根文件系统部署及完整的每种安装指南,请参阅 [CONTAINERIZATION.md](./CONTAINERIZATION.md)。
```bash
docker run --rm --name deeptutor \
-p 127.0.0.1:3782:3782 \
-v deeptutor-data:/app/data \
ghcr.io/hkuds/deeptutor:latest
```
> **只需发布 `3782` 端口。** 浏览器只与前端源通信;Next.js 中间件(`web/proxy.ts`)在**容器内部**将 `/api/*` 和 `/ws/*` 转发给 FastAPI 后端。发布 `8001``-p 127.0.0.1:8001:8001`)是可选的 — 仅在需要用 curl 或脚本直接访问 API 时才有用。
打开 [http://127.0.0.1:3782](http://127.0.0.1:3782)。容器首次启动时会创建 `/app/data/user/settings/*.json`;通过 Web Settings 页面配置模型提供商。配置、API Key、日志、工作区文件、记忆和知识库均持久化在 `deeptutor-data` 卷中。
- **不同宿主机端口:** 修改每个 `-p host:container` 映射的左侧(例如 `-p 127.0.0.1:8088:3782`)。如果修改了 `/app/data/user/settings/system.json` 中容器侧的端口,重启并更新映射右侧以匹配。
- **后台运行:** 添加 `-d`,然后用 `docker logs -f deeptutor` 查看日志,`docker stop deeptutor` 停止,重用名称前执行 `docker rm deeptutor``deeptutor-data` 卷在重启之间保留设置和工作区。
**远程 Docker / 反向代理:** 浏览器只与前端源(`:3782`)通信;容器内的 Next.js 中间件在服务端将 `/api/*``/ws/*` 转发给后端服务器。对于常见的单容器场景,完全不需要配置 API base — 只需将反向代理 / TLS 终止器指向 `:3782` 即可。只有在**拆分部署**(后端在独立容器/主机上)时才需要设置 API base:将 `data/user/settings/system.json` 中的 `next_public_api_base` 设置为前端服务器用于访问后端的内网地址(它在服务端读取,永远不会发送到浏览器)。
```json
{
"next_public_api_base": "http://backend:8001"
}
```
`next_public_api_base_external`(及其别名 `public_api_base`)作为低优先级的备用配置被接受。CORS 使用前端**来源**,而非 API URL。禁用认证时,DeepTutor 默认允许普通 HTTP/HTTPS 浏览器来源。启用认证时,需添加精确的前端来源:
```json
{
"cors_origins": ["https://deeptutor.example.com"]
}
```
<details>
<summary><b>连接宿主机上的 Ollama / LM Studio / llama.cpp / vLLM / Lemonade</b></summary>
在 Docker 内部,`localhost` 指容器本身,而非宿主机。要连接宿主机上的模型服务,使用宿主机网关(推荐):
```bash
docker run --rm --name deeptutor \
-p 127.0.0.1:3782:3782 -p 127.0.0.1:8001:8001 \
--add-host=host.docker.internal:host-gateway \
-v deeptutor-data:/app/data \
ghcr.io/hkuds/deeptutor:latest
```
然后在 **Settings → Models** 中,将提供商 Base URL 指向 `host.docker.internal`
- Ollama LLM: `http://host.docker.internal:11434/v1`
- Ollama 嵌入: `http://host.docker.internal:11434/api/embed`
- LM Studio: `http://host.docker.internal:1234/v1`
- llama.cpp: `http://host.docker.internal:8080/v1`
- Lemonade: `http://host.docker.internal:13305/api/v1`
Docker DesktopmacOS/Windows)通常无需 `--add-host` 即可解析 `host.docker.internal`。在 Linux 上,该标志是在现代 Docker Engine 上创建该主机名的便携方式。
**Linux 替代方案 — 宿主机网络:** 添加 `--network=host` 并去掉 `-p` 标志。容器直接共享宿主机网络,打开 [http://127.0.0.1:3782](http://127.0.0.1:3782)(或 `system.json` 中的 `frontend_port`),宿主机服务可通过普通 localhost URL(如 `http://127.0.0.1:11434/v1`)访问。注意宿主机网络会将容器端口直接暴露在宿主机上,可能与现有服务冲突 — 若需保持在回环地址上,可设置 `BACKEND_HOST=127.0.0.1``FRONTEND_HOST=127.0.0.1`(详见 [CONTAINERIZATION.md](./CONTAINERIZATION.md))。
</details>
</details>
<details>
<summary><b>方式四 — 仅 CLI</b> · 无 Web UI,基于源码安装</summary>
当不需要 Web UI 时使用。仅 CLI 包从源码安装,不从 PyPI 安装。
```bash
git clone https://github.com/HKUDS/DeepTutor.git
cd DeepTutor
# 创建 venvmacOS/Linux)。Windows PowerShell
# py -3.11 -m venv .venv-cli ; .\.venv-cli\Scripts\Activate.ps1
python3 -m venv .venv-cli && source .venv-cli/bin/activate
python -m pip install --upgrade pip
python -m pip install -e ./packaging/deeptutor-cli
deeptutor init --cli
deeptutor chat
```
`deeptutor init --cli` 与完整应用共享同一 `data/user/settings/` 布局,但跳过后端/前端端口提示,并默认将嵌入设为**关闭**(如计划使用 `deeptutor kb …` 或 RAG 工具,选择 `Yes`)。它仍会写入完整的运行时布局(`system.json``auth.json``integrations.json``model_catalog.json``main.yaml``agents.yaml`),并提示选择活跃的 LLM 提供商和模型。
<details>
<summary><b>常用命令</b></summary>
```bash
deeptutor chat # 交互式 REPL
deeptutor chat --capability deep_solve --tool rag --kb my-kb
deeptutor run chat "解释傅里叶变换"
deeptutor run deep_solve "Solve x^2 = 4" --tool rag --kb my-kb
deeptutor kb create my-kb --doc textbook.pdf
deeptutor memory show
deeptutor config show
```
</details>
本地 `deeptutor-cli` 安装不包含 Web 资产或服务器依赖。请保留源码仓库 — 可编辑安装指向它。若之后需要添加 Web 应用,从同一工作区安装 PyPI 包(方式一),并运行 `deeptutor init` + `deeptutor start`
</details>
<details>
<summary><b>代码执行沙箱(Office 技能)</b> · 运行 docx / pdf / pptx / xlsx 的模型生成代码</summary>
内置的 Office 技能 — **docx / pdf / pptx / xlsx** — 通过让模型编写短 Python 脚本(`python-docx``reportlab``openpyxl` 等),经 `exec` / `code_execution` 工具运行,并返回下载 URL 来工作。这些工具在沙箱后端激活时自动挂载,在每种部署形式下**默认**均已激活:
- **本地(方式一 / 二)和 Docker(方式三,单容器):** 受限子进程沙箱运行模型代码(本地在宿主机上,Docker 在容器内部 — 容器本身即隔离边界)。
- **docker-compose** 通过 `DEEPTUTOR_SANDBOX_RUNNER_URL` 路由至加固的最小权限**运行器 sidecar**`Dockerfile.runner`) — 安全性最强,有 sidecar 时自动优先使用。
子进程沙箱由 `data/user/settings/system.json` 中的 `sandbox_allow_subprocess` 设置控制(默认 `true`)。在宿主机上运行模型生成的代码是一个真实的信任决策 — 将其设为 `false`(或导出 `DEEPTUTOR_SANDBOX_ALLOW_SUBPROCESS=0`)可禁用宿主机侧执行,代价是 Office 技能将无法生成文件。
</details>
<details>
<summary><b>配置参考</b> — <code>data/user/settings/</code> 下的配置文件(JSON/YAML</summary>
`data/user/settings/` 下的所有内容均为纯 JSON/YAML 格式。推荐使用浏览器中的 **Settings** 页面进行编辑。
| 文件 | 用途 |
|:---|:---|
| `model_catalog.json` | LLM、嵌入和搜索提供商配置;API Key;活跃模型 |
| `system.json` | 后端/前端端口、公开 API 基础地址、CORS、SSL 校验、附件目录 |
| `auth.json` | 可选认证开关、用户名、密码哈希、token/cookie 设置 |
| `integrations.json` | 可选的 PocketBase 和 sidecar 集成设置 |
| `interface.json` | UI 语言 / 主题 / 侧边栏偏好 |
| `main.yaml` | 运行时行为默认值和路径注入 |
| `agents.yaml` | 能力/工具的 temperature 和 token 设置 |
项目根目录的 `.env` **不会**作为应用配置文件被读取。最简模型配置:打开 **Settings → Models**,添加 LLM 配置(Base URL / API Key / 模型名称),然后保存。仅在计划使用知识库 / RAG 功能时才需要添加嵌入配置。
</details>
## 📖 探索 DeepTutor
从日常使用的主要界面开始:Chat、Partners、My Agents、Co-Writer、Book、知识中心、学习空间、Memory 和 Settings。之后将介绍用于共享隔离工作区的多用户部署。
<div align="center">
<img src="../../assets/figs/web-1.4.6+/OVERVIEW.png" alt="DeepTutor 主页 — 带有侧边栏所有入口的 Chat 工作区" width="900">
</div>
<details>
<summary><b>🏗️ 系统架构</b></summary>
<div align="center">
<img src="../../assets/figs/system/system%20architecture.png" alt="DeepTutor 系统架构" width="900">
</div>
</details>
<details>
<summary><b>💬 Chat — 真正好用的智能体循环</b></summary>
Chat 是默认能力,也是大多数工作的起点。单个对话线程可以正常交流、调用工具、基于选定知识库进行检索、读取附件、生成图像、调用子智能体、写入笔记本记录,并在多轮对话中保持相同的上下文。
<div align="center">
<img src="../../assets/figs/web-1.4.6+/home/00-overview.png" alt="DeepTutor 聊天工作区" width="900">
</div>
循环设计刻意保持简单:模型按轮次思考,在有用时调用工具,观察结果,最终以不调用工具的消息结束。`ask_user` 是特殊工具 — 智能体不是凭空猜测,而是可以暂停当前轮次,提出结构化的澄清问题,在你回答后恢复。
<div align="center">
<img src="../../assets/figs/system/chat-agent-loop.png" alt="DeepTutor 聊天智能体循环" width="900">
</div>
用户可切换的工具有 `brainstorm``web_search``paper_search``reason``geogebra_analysis` — 配置了对应生成模型后还有 `imagegen``videogen`。上下文工具如 `rag``read_source``read_memory``write_memory``read_skill``load_tools``exec``web_fetch``ask_user``list_notebook``write_note``github``consult_subagent` 会在当前轮次具备相应上下文时自动挂载。
上下文分为两类:**粘性会话上下文**(子智能体、知识库、人格预设、模型、语音)存在于编辑器工具栏,在各轮次间持续保留;**一次性引用**(文件、聊天历史、书籍、笔记本、题库、导入的智能体)通过 `+` 菜单添加,仅用于单次对话轮次。
Chat 也是进入更深层能力的入口:**Quiz** 用于题目生成,**Research** 用于带引用的报告,**Visualize** 用于图表 / 示意图 / 动画,以及 *更多能力* 下的 **Solve**(有步骤的推理)和 **Mastery Path**(学习计划流程)。
</details>
<details>
<summary><b>🤝 Partner — 运行在同一大脑上的持久伴侣</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/partners/00-partners%20overview.png" alt="DeepTutor Partners 工作区" width="900">
</div>
Partners 是拥有独立灵魂、模型策略、知识库、记忆和渠道的持久伴侣。它们不是独立的机器人引擎:每条入站的 Web 或 IM 消息都会成为在 Partner 作用域工作区内的一次普通 `ChatOrchestrator` 对话轮次。Partner 就是"一个有个性和电话号码的聊天"。
<div align="center">
<img src="../../assets/figs/system/partners-architecture.png" alt="DeepTutor Partners 架构" width="900">
</div>
每个 Partner 拥有 `SOUL.md`、模型选择、渠道、工具策略和分配的知识库。知识库、技能和笔记本会被复制到 `data/partners/<id>/workspace/`,因此相同的 RAG、技能、笔记本和记忆工具无需特殊处理即可正常工作。Partner 可以读取其拥有者的记忆,但只能写入自己的记忆。
<div align="center">
<img src="../../assets/figs/web-1.4.6+/partners/02-IM%20config%20for%20each%20partner.png" alt="每个 Partner 的 IM 渠道配置" width="900">
</div>
渠道层基于 Schema 驱动,根据已安装的额外依赖和配置的凭证,可连接飞书、Telegram、Slack、Discord、钉钉、QQ/NapCat、企业微信、WhatsApp、Zulip、Mattermost、Matrix、Mochat 和 Microsoft Teams 等 IM 平台。Partner 也可以作为子智能体连接,并从普通聊天轮次中调用 — 详见下方的**我的智能体**。
</details>
<details>
<summary><b>🧑‍🚀 我的智能体 — 调用与导入其他智能体</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/myagents/00-overview.png" alt="DeepTutor 我的智能体工作区" width="900">
</div>
"我的智能体"将其他智能体转化为 DeepTutor 的上下文,具备两种不同的功能。**连接实时智能体** — 连接你机器上的 Claude Code 或 Codex CLI,或你的某个 Partner,在聊天轮次中调用它:DeepTutor 实际上会*运行*另一个智能体,并通过 `consult_subagent` 工具将其工作流式传输到 Activity 面板。通过智能体选项(或输入 `@`)选择它,并设置调用可进行的最大轮数。
<div align="center">
<img src="../../assets/figs/web-1.4.6+/home/08-subagent%20demo%20with%20claude%20code.png" alt="实时调用 Claude Code 子智能体" width="900">
</div>
**导入历史对话** — 将已有的 Claude Code 和 Codex 历史记录作为命名的、可搜索的、可续聊的智能体导入。选择要导入的日期范围;刷新时自动重新同步。通过 `+` → 我的智能体在任意聊天轮次中引用已导入的对话,DeepTutor 会将其作为第三方对话记录读取 — 它始终是*对方的*对话,不会被 DeepTutor 以自己的口吻解读。
</details>
<details>
<summary><b>✍️ Co-Writer — 感知选区的 Markdown 写作台</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/co-writer/00-overview.png" alt="DeepTutor Co-Writer 工作区" width="900">
</div>
Co-Writer 是一个分屏 Markdown 工作区,适用于报告、教程、笔记和长篇学习素材的创作。文档自动保存并实时渲染预览(KaTeX 数学公式、图表围栏),草稿完成后可保存回笔记本成为可复用的上下文。
<div align="center">
<img src="../../assets/figs/web-1.4.6+/co-writer/01-edit%20panel.png" alt="Co-Writer 编辑器与实时预览" width="900">
</div>
其核心理念是**精准编辑**:选中一段文字,让 DeepTutor 对其进行改写、扩展或缩短。编辑智能体可以基于知识库或网络证据进行修改,保留工具调用追踪,并以接受/拒绝差异对比的形式展示每处变更 — 直到你批准后才会生效。
</details>
<details>
<summary><b>📖 Book — 从你的素材生成活书</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/book/00-book_overview.png" alt="DeepTutor 书籍库" width="900">
</div>
Book 将选定的来源转化为交互式**活书** — 不是静态 PDF,而是由类型化块构建的阅读环境。书籍可以从知识库、笔记本、题库或聊天历史开始创建;创建流程会在内容生成前提出章节大纲,让你审查结构,而不是被动接受一次性的盲目输出。
<p align="center">
<img src="../../assets/figs/web-1.4.6+/book/01-book-demo-quiz%20card.png" alt="Book 测验块" width="31%">
&nbsp;
<img src="../../assets/figs/web-1.4.6+/book/02-book-demo-manim%20video.png" alt="Book Manim 动画块" width="31%">
&nbsp;
<img src="../../assets/figs/web-1.4.6+/book/03-book-demo%20interactive%20module.png" alt="Book 交互式组件块" width="31%">
</p>
每章编译为类型化块 — 文本、标注、测验、闪卡、时间轴、代码、图形、交互式 HTML、动画、概念图、深度解析和用户笔记 — 每页都有独立的 Page Chat。块可编辑:插入、移动、重新生成或切换块类型,无需重写整章。维护命令如 `deeptutor book health``deeptutor book refresh-fingerprints` 有助于检测来源知识库与已编译页面的漂移情况。
</details>
<details>
<summary><b>📚 知识中心 — 多引擎 RAG 知识库</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/knowledge/00-overview.png" alt="DeepTutor 知识中心" width="900">
</div>
知识库是 RAG 背后的文档集合 — 为 Chat 对话、Co-Writer 编辑、Book 生成和 Partner 对话提供依据。其独特之处在于**检索引擎的选择**:**LlamaIndex**(默认,本地向量 + BM25)、**PageIndex**(托管,支持页面级引用的推理检索)、**GraphRAG** 和 **LightRAG**(知识图谱检索)、**LightRAG Server**(将检索卸载至你通过 HTTP 连接的外部 LightRAG 实例),或直接在原位读写的链接 **Obsidian** vault。每个 KB 绑定到单一引擎。
<div align="center">
<img src="../../assets/figs/web-1.4.6+/knowledge/01-create%20knowledge%20base.png" alt="创建知识库" width="900">
</div>
创建 KB 时,可以选择**新建**(上传文档并构建全新索引)或**链接已有**(复用在其他地方构建的索引,原位读取无需重新索引)。重新索引会写入新的平铺 `version-N` 目录并保留旧版本,因此重建过程中现有索引不会被破坏。即使知识库处于 **error** 状态,也可以单独移除其中一份文档 — 无需完整地删除重建,就能丢弃解析失败的文件。文档解析 — 纯文本、MinerU、Docling、markitdown 或 PyMuPDF4LLM — 在 **Settings → Knowledge Base** 中选择,本地模型下载默认关闭。CLI 通过 `deeptutor kb list``info``create``add``search``set-default``delete` 来管理完整生命周期。
</details>
<details>
<summary><b>🌐 学习空间 — 技能、人格预设与可复用上下文</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/learning-space/00-overview.png" alt="DeepTutor 学习空间中心" width="900">
</div>
学习空间是知识库和个性化层 — 持久化内容的存放之处。**对话与素材**保存聊天历史、笔记本和题库(每道保存的题目包含你的答案、参考答案和解析)。**个性化**保存掌握路径、人格预设(如*同伴*、*研究助手*、*教师*等行为预设)和技能(模型按需读取的 `SKILL.md` 剧本)。这里的所有内容均可在 Chat、Partners、Co-Writer 和 Book 中复用。
<div align="center">
<img src="../../assets/figs/web-1.4.6+/learning-space/07-%20download%20skills%20from%20eduhub.png" alt="从 EduHub 导入技能" width="900">
</div>
你不必自己编写每个技能 — **从 EduHub 导入**可浏览社区目录,通过安全门将技能直接下载到你的库中(详见[生态系统](#-生态系统--eduhub-与技能社区))。
</details>
<details>
<summary><b>🧠 Memory — 可审计的个性化记忆</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/memory/00-overview.png" alt="DeepTutor 记忆概览" width="900">
</div>
Memory 是一个基于文件、三层结构的系统,你可以读取、整理和审计它 — 刻意设计为*非*隐藏的向量库。**L1** 是工作区镜像加仅追加的事件追踪(`trace/<surface>/<date>.jsonl`);**L2** 是按表面整理的事实(`L2/<surface>.md`);**L3** 是跨表面的综合(`L3/<profile|recent|scope|preferences>.md`)。由于 L2 引用 L1,L3 引用 L2,你的档案中没有任何不可追溯的内容。
<div align="center">
<img src="../../assets/figs/web-1.4.6+/memory/01-3%20layer%20memory%20graph.png" alt="DeepTutor 记忆图谱" width="900">
</div>
Memory Graph 展示整个金字塔 — L3 综合位于中心,L2 在中间圆环,L1 追踪在外圈 — 你可以将任何综合结论追溯到其背后的精确原始事件。Memory 在 `chat``notebook``quiz``kb``book`、partner 和 `cowriter` 表面进行追踪;整合器的更新 / 审计 / 去重预算可在 **Settings → Memory** 中调整。
</details>
<details>
<summary><b>⚙️ Settings — 统一的控制面板</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/settings/00-setting%20overview.png" alt="DeepTutor 设置中心" width="900">
</div>
Settings 是操作控制面板,带有实时状态条(后端、LLM、嵌入、搜索)和每个区域的配置卡:**外观**(主题 + UI 语言)、**网络**(API 基础地址、端口、CORS)、**模型**(LLM、嵌入、搜索、文字转语音、语音转文字、图像生成、视频生成)、**知识库**(文档解析引擎)、**聊天**(工具、MCP 服务器、每个能力的参数)、**Partners 与智能体**(可在对话轮次中调用的子智能体),以及**记忆**(整合器预算)。
<div align="center">
<img src="../../assets/figs/web-1.4.6+/settings/01-appearance%20settings.png" alt="DeepTutor 外观设置与主题" width="900">
</div>
大多数部分采用草稿-应用流程,因此你可以在提交前测试提供商配置。开箱即提供四种主题 — Default、Cream、Dark 和 Glass。项目根目录的 `.env` 文件被刻意忽略;运行时配置存储在 `data/user/settings/*.json` 下,除非 `DEEPTUTOR_HOME``deeptutor start --home` 将应用指向其他位置。
</details>
<details>
<summary><b>👥 多用户 — 共享部署</b> · 可选认证,隔离的用户工作区</summary>
认证默认**关闭** — DeepTutor 以单用户模式运行。开启后,单个 `data/` 目录树可同时托管管理员工作区、隔离的用户工作区和 Partner 工作区:
```text
data/
├── user/ # 管理员工作区 + 全局设置
├── users/<uid>/ # 用户作用域:聊天历史、记忆、笔记本、知识库
├── partners/<id>/workspace/ # Partner(合成用户)作用域
└── system/ # auth/users.json · grants/<uid>.json · audit/usage.jsonl
```
**第一个注册用户成为管理员**,拥有模型目录、提供商凭证、共享知识库、技能和用户授权的管理权。其他所有人获得隔离的工作区和删减版的 Settings 页面 — 管理员分配的模型、知识库和技能以作用域只读选项的形式出现,原始 API Key 不可见。
**启用方式:**`data/user/settings/auth.json` 中开启认证,重启 `deeptutor start`,在 `/register` 注册第一个管理员,然后从 `/admin/users` 添加用户,并通过授权分配模型、知识库、技能、Partner、工具/MCP 策略和代码执行权限。
> PocketBase 仍为单用户集成 — 多用户部署时请将 `integrations.pocketbase_url` 留空,除非你已接入外部用户存储。
</details>
## ⌨️ DeepTutor CLI — 智能体原生界面
一个 `deeptutor` 可执行文件,两种使用方式:供习惯在终端中工作的人使用的交互式 **REPL**,以及供将 DeepTutor 作为工具来驱动的其他智能体使用的结构化 **JSON** 输出。两种方式共享相同的能力、工具和知识库。
<details>
<summary><b>自己驱动</b></summary>
`deeptutor chat` 打开交互式 REPL`deeptutor run <capability> "<message>"` 执行单次对话并退出。两者共享相同的 `--capability``--tool``--kb``--config` 标志。
```bash
deeptutor chat # 交互式 REPL
deeptutor chat --capability deep_solve --kb my-kb --tool rag
deeptutor run chat "解释傅里叶变换" --tool rag --kb textbook
deeptutor run deep_research "调研 2026 年 RAG 论文" \
--config mode=report --config depth=standard
```
Web 应用的所有功能在这里都有对应 — 知识库(`kb`)、会话(`session`)、Partners`partner`)、技能(`skill`)、笔记本、记忆和配置。完整列表见下方。
</details>
<details>
<summary><b>让智能体驱动</b></summary>
DeepTutor 专为*被其他智能体操作*而设计。在任何 `run` 命令中添加 `--format json`,每个轮次将流式输出 **NDJSON — 每行一个事件**`content``tool_call``tool_result``done` 等),每行带有其 `session_id` 标记。运行是无头安全的:无 TTY 时,`ask_user` 暂停会以空回复自动解决,而不是挂起。
```bash
# 单次执行,机器可读
deeptutor run deep_solve "Find d/dx[sin(x^2)]" --tool reason --format json
# 在单个有状态会话中链接多轮 — 捕获 id 并复用
SID=$(deeptutor run deep_research "调研 2026 年 RAG 论文" \
--config mode=report --config depth=standard --format json \
| jq -r 'select(.type=="done").session_id')
deeptutor run deep_question "就那篇调研测验我" --session "$SID" --format json
```
仓库根目录附带 [`SKILL.md`](SKILL.md) — 约 150 行的交接文档,让任何支持工具调用的 LLM 一次性掌握所有接口。将其传递给 Claude Code、Codex 或 OpenCode(它们会自动读取 `SKILL.md`),或将 `deeptutor run` 包装为 LangChain / AutoGen 循环中的工具。完整示例:[Agent Handoff](https://deeptutor.info/docs/cli/agent-handoff/)。
</details>
<details>
<summary><b>命令参考</b></summary>
| 命令 | 说明 |
|:---|:---|
| `deeptutor init` | 为当前工作区创建或更新 `data/user/settings` |
| `deeptutor start [--home PATH]` | 同时启动后端 + 前端 |
| `deeptutor serve [--port PORT]` | 仅启动 FastAPI 后端 |
| `deeptutor run <capability> <message>` | 运行单次能力对话(`chat``deep_solve``deep_question``deep_research``visualize``math_animator``mastery_path`);添加 `--format json` 可获得 NDJSON 输出 |
| `deeptutor chat` | 交互式 REPL,支持能力、工具、知识库、笔记本和历史控制 |
| `deeptutor partner list/create/start/stop` | 管理 IM 连接的 Partners |
| `deeptutor kb list/info/create/add/search/set-default/delete` | 管理 LlamaIndex 知识库 |
| `deeptutor skill search/install/list/remove/login/logout/publish/update` | 管理技能、从 Hub 安装并发布自己的技能(默认 `eduhub:<slug>`,详见生态系统) |
| `deeptutor memory show/clear` | 查看 L2/L3 记忆文档或清除 L1/全部记忆 |
| `deeptutor session list/show/open/rename/delete` | 管理共享会话 |
| `deeptutor notebook list/create/show/add-md/replace-md/remove-record` | 从 Markdown 文件管理笔记本 |
| `deeptutor book list/health/refresh-fingerprints` | 查看书籍并刷新来源指纹 |
| `deeptutor plugin list/info` | 查看已注册的工具和能力 |
| `deeptutor config show` | 打印配置摘要 |
| `deeptutor provider login <provider>` | 提供商认证(`openai-codex` OAuth 登录;`github-copilot` 验证现有 Copilot 认证会话) |
</details>
<details>
<summary><b>仅 CLI 发行版</b></summary>
仅 CLI 包位于 `packaging/deeptutor-cli`。在此代码仓库中,从源码安装:
```bash
python -m pip install -e ./packaging/deeptutor-cli
```
尚未发布到 PyPI,因此[快速开始](#-快速开始)部分保留了源码安装路径。
</details>
## 🧩 生态系统 — EduHub 与技能社区
DeepTutor 技能使用开放的 **Agent-Skills** 格式 — 一个包含 `SKILL.md` 剧本(YAML frontmatter + Markdown)和可选参考文件的文件夹。该格式与 DeepTutor 无关,因此任何支持该格式的注册表都可以成为你的技能库来源。DeepTutor 内置了 **[EduHub](https://eduhub.deeptutor.info/)** — 我们自己的教育技能注册表 — 作为默认 Hub。
<details>
<summary><b>EduHub — DeepTutor 的技能生态</b></summary>
[**EduHub**](https://eduhub.deeptutor.info/) 是 DeepTutor 为分享教学导向的智能体技能而创建的社区 Hub — 苏格拉底式导师、闪卡生成器、作文反馈、考试蓝图、概念讲解器等。它内置于 DeepTutor,无需任何配置:裸 slug 或 `eduhub:` 前缀均可解析到它。
**查找与安装** — 在浏览器中,打开**学习空间 → 技能 → 从 EduHub 导入**,浏览目录并将技能直接下载到你的库中。从终端:
```bash
deeptutor skill search "socratic tutor" # 在 EduHub(默认 Hub)中搜索
deeptutor skill install socratic-tutor # 获取 → 验证 → 注册
deeptutor skill install eduhub:socratic-tutor@1.2.0 # 指定 Hub 和版本
deeptutor skill list # 本地技能及其 Hub 来源
```
**发布自己的技能** — 打包一个 `SKILL.md` 并分享给社区:
```bash
deeptutor skill login # 浏览器登录 EduHub
deeptutor skill publish ./my-skill # 交互式:选择分类 + 标签,然后上传
deeptutor skill update # 回滚或发布新版本
```
EduHub 也是一个独立的、ClawHub 兼容的注册表,因此非 DeepTutor 的智能体(Claude Code、Codex 等)可以通过 `eduhub` CLI 直接使用它 — `npx eduhub install socratic-tutor`
</details>
<details>
<summary><b>导入安全门</b></summary>
无论来源如何,每次导入在触及你的工作区之前都会经过**相同的安全门**:
- 首先检查注册表的**安全验证结果** — 被标记的包将被拒绝,除非你传入 `--allow-unverified`
- 压缩包被防御性解压(防 zip-slip / zip-bomb)并经过文本/脚本**后缀白名单**过滤,因此二进制文件永远不会落入工作区;
- frontmatter 被规范化并**去除** `always:`,因此下载的技能永远无法强制将自己注入每个系统提示;
- 来源信息 — Hub、版本、验证结果和安装时间 — 被写入 `.hub-lock.json` 以供审计和更新。
在多用户部署中,安装为管理员专属操作:新技能进入管理员目录,在授权分配前对其他用户不可见,管理员可以在推广前进行审核。
</details>
<details>
<summary><b>同样兼容 ClawHub</b></summary>
因为 DeepTutor 支持开放的 Agent-Skills 格式,**[ClawHub](https://clawhub.ai/)** 也是一等来源 — 它与 EduHub 并列内置。使用 Hub 前缀选择:
```bash
deeptutor skill search "git release notes" --hub clawhub
deeptutor skill install clawhub:git-release-notes@1.0.1
```
`settings/skill_hubs.json` 中添加更多注册表:`type: "clawhub"` 条目指向任何兼容的 HTTP APIEduHub 和 ClawHub 都支持),`type: "command"` 包装注册表自带的任何获取 CLI`"default"` 选择用于裸 slug 的 Hub。所有这些来源都经过同一个导入安全门。
</details>
## 🌐 社区
### 📮 联系方式
DeepTutor 是一个由 [HKUDS](https://github.com/HKUDS) 团队中的 [Bingxi Zhao](https://github.com/pancacake) 主导的开源项目,以**完全开源的形式**持续迭代,与社区共同构建。迄今为止,我们**没有**任何形式的付费在线产品。欢迎通过 **bingxizhao39@gmail.com** 联系我们,探讨想法或合作。
### 🙏 致谢
衷心感谢香港大学数据智能实验室主任 [**Chao Huang**](https://sites.google.com/view/chaoh) 的大力支持,以及 HKUDS 实验室同学们的热心相助 — 特别是 [**Jiahao Zhang**](https://github.com/zzhtx258)、[**Zirui Guo**](https://github.com/LarFii) 和 [**Xubin Ren**](https://github.com/Re-bin)。我们也对**开源社区**深表感激:你们的 Star、Issue、Pull Request 和讨论,每天都在塑造 DeepTutor。
DeepTutor 也站在众多优秀开源项目的肩膀上,它们给予了我们工具和灵感:
| 项目 | 角色 / 启发 |
|:---|:---|
| [**LlamaIndex**](https://github.com/run-llama/llama_index) | RAG 流水线和文档索引基础 |
| [**nanobot**](https://github.com/HKUDS/nanobot) | 驱动原版 TutorBot 的超轻量智能体引擎 *(HKUDS)* |
| [**LightRAG**](https://github.com/HKUDS/LightRAG) | 简单快速的 RAG *(HKUDS)* |
| [**AutoAgent**](https://github.com/HKUDS/AutoAgent) | 零代码智能体框架 *(HKUDS)* |
| [**AI-Researcher**](https://github.com/HKUDS/AI-Researcher) | 自动化研究流水线 *(HKUDS)* |
| [**OpenClaw**](https://github.com/openclaw/openclaw) | 支撑 ClawHub 的开放智能体网关与技能生态 |
| [**Codex**](https://github.com/openai/codex) | 启发我们 CLI 工作流的智能体原生编程 CLI |
| [**Claude Code**](https://github.com/anthropics/claude-code) | 启发 DeepTutor 智能体循环的智能体编程 CLI |
| [**ManimCat**](https://github.com/Wing900/ManimCat) | Math Animator 的 AI 驱动数学动画生成 |
### 🗺️ 路线图与贡献
我们希望 DeepTutor 持续迭代与进步 — 并最终成为我们回馈开源社区的礼物。我们的[**路线图**](https://github.com/HKUDS/DeepTutor/issues/498)持续更新;欢迎在那里为议题投票或提出新想法。如果你想贡献,请查看[**贡献指南**](CONTRIBUTING.md),了解分支策略、编码规范及参与方式。
<div align="center">
我们希望 DeepTutor 成为送给社区的一份礼物。🎁
<a href="https://github.com/HKUDS/DeepTutor/graphs/contributors">
<img src="https://contrib.rocks/image?repo=HKUDS/DeepTutor&max=999" alt="贡献者" />
</a>
</div>
<div align="center">
<a href="https://www.star-history.com/#HKUDS/DeepTutor&type=timeline&legend=top-left">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=HKUDS/DeepTutor&type=timeline&theme=dark&legend=top-left" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=HKUDS/DeepTutor&type=timeline&legend=top-left" />
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=HKUDS/DeepTutor&type=timeline&legend=top-left" />
</picture>
</a>
</div>
<p align="center">
<a href="https://www.star-history.com/hkuds/deeptutor">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/badge?repo=HKUDS/DeepTutor&theme=dark" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/badge?repo=HKUDS/DeepTutor" />
<img alt="Star History Rank" src="https://api.star-history.com/badge?repo=HKUDS/DeepTutor" />
</picture>
</a>
</p>
<div align="center">
基于 [Apache License 2.0](LICENSE) 许可证。
<p>
<img src="https://visitor-badge.laobi.icu/badge?page_id=HKUDS.DeepTutor&style=for-the-badge&color=00d4ff" alt="访问量">
</p>
</div>
+719
View File
@@ -0,0 +1,719 @@
<div align="center">
<p align="center"><img src="../../assets/figs/logo/logo.png" alt="DeepTutor logo" height="56" style="vertical-align: middle;">&nbsp;<img src="../../assets/figs/logo/banner.png" alt="DeepTutor" height="48" style="vertical-align: middle;"></p>
# DeepTutor: Tutoría Personalizada de Por Vida
<p align="center">
<a href="https://deeptutor.info" target="_blank"><img alt="Docs — deeptutor.info" src="https://img.shields.io/badge/Docs-deeptutor.info%20%E2%86%97-0A0A0A?style=for-the-badge&labelColor=F5F5F4" height="36"></a>
</p>
<p align="center">
<a href="https://trendshift.io/repositories/17099?utm_source=repository-badge&amp;utm_medium=badge&amp;utm_campaign=badge-repository-17099" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/repositories/17099" alt="HKUDS%2FDeepTutor | Trendshift" width="250" height="55"/></a>&nbsp;
<a href="https://trendshift.io/repositories/17099?utm_source=trendshift-badge&amp;utm_medium=badge&amp;utm_campaign=badge-trendshift-17099" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/17099/daily" alt="HKUDS%2FDeepTutor | Trendshift" width="250" height="55"/></a>&nbsp;
<a href="https://trendshift.io/repositories/17099?utm_source=trendshift-badge&amp;utm_medium=badge&amp;utm_campaign=badge-trendshift-17099" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/17099/weekly?language=Python" alt="HKUDS%2FDeepTutor | Trendshift" width="250" height="55"/></a>
</p>
<p align="center">
<a href="../../README.md"><img alt="English" height="40" src="https://img.shields.io/badge/English-CDCFD4"></a>&nbsp;
<a href="README_CN.md"><img alt="简体中文" height="40" src="https://img.shields.io/badge/简体中文-CDCFD4"></a>&nbsp;
<a href="README_JA.md"><img alt="日本語" height="40" src="https://img.shields.io/badge/日本語-CDCFD4"></a>&nbsp;
<a href="README_ES.md"><img alt="Español" height="40" src="https://img.shields.io/badge/Español-BCDCF7"></a>&nbsp;
<a href="README_FR.md"><img alt="Français" height="40" src="https://img.shields.io/badge/Français-CDCFD4"></a>&nbsp;
<a href="README_AR.md"><img alt="Arabic" height="40" src="https://img.shields.io/badge/Arabic-CDCFD4"></a>&nbsp;
<a href="README_RU.md"><img alt="Русский" height="40" src="https://img.shields.io/badge/Русский-CDCFD4"></a>&nbsp;
<a href="README_HI.md"><img alt="Hindi" height="40" src="https://img.shields.io/badge/Hindi-CDCFD4"></a>&nbsp;
<a href="README_PT.md"><img alt="Português" height="40" src="https://img.shields.io/badge/Português-CDCFD4"></a>&nbsp;
<a href="README_TH.md"><img alt="Thai" height="40" src="https://img.shields.io/badge/Thai-CDCFD4"></a>&nbsp;
<a href="README_PL.md"><img alt="Polski" height="40" src="https://img.shields.io/badge/Polski-CDCFD4"></a>
</p>
[![Python 3.11+](https://img.shields.io/badge/Python-3.11%2B-3776AB?style=flat-square&logo=python&logoColor=white)](https://www.python.org/downloads/)
[![Next.js 16](https://img.shields.io/badge/Next.js-16-000000?style=flat-square&logo=next.js&logoColor=white)](https://nextjs.org/)
[![License](https://img.shields.io/badge/License-Apache_2.0-blue?style=flat-square)](../../LICENSE)
[![GitHub release](https://img.shields.io/github/v/release/HKUDS/DeepTutor?style=flat-square&color=brightgreen)](https://github.com/HKUDS/DeepTutor/releases)
[![arXiv](https://img.shields.io/badge/arXiv-2604.26962-b31b1b?style=flat-square&logo=arxiv&logoColor=white)](https://arxiv.org/abs/2604.26962)
[![Discord](https://img.shields.io/badge/Discord-Community-5865F2?style=flat-square&logo=discord&logoColor=white)](https://discord.gg/eRsjPgMU4t)
[![Feishu](https://img.shields.io/badge/Feishu-Group-00D4AA?style=flat-square&logo=feishu&logoColor=white)](../../Communication.md)
[![WeChat](https://img.shields.io/badge/WeChat-Group-07C160?style=flat-square&logo=wechat&logoColor=white)](https://github.com/HKUDS/DeepTutor/issues/78)
[Características](#-características-principales) · [Comenzar](#-comenzar) · [Explorar](#-explorar-deeptutor) · [CLI](#-deeptutor-cli--interfaz-nativa-de-agentes) · [Ecosistema](#-ecosistema--eduhub-y-la-comunidad-de-skills) · [Comunidad](#-comunidad)
</div>
---
> 🤝 **¡Damos la bienvenida a cualquier tipo de contribución!** Vota en los elementos del roadmap o propone nuevos en [`Roadmap`](https://github.com/HKUDS/DeepTutor/issues/498), y consulta nuestra [Guía de Contribución](../../CONTRIBUTING.md) para la estrategia de ramas, estándares de código y cómo comenzar.
### 📰 Noticias
- **2026-05-22** 🌐 Sitio de documentación oficial disponible en [**deeptutor.info**](https://deeptutor.info/) — guías, referencias y tours de capacidades, todo en un solo lugar.
- **2026-04-19** 🎉 ¡20k estrellas en 111 días! Gracias por el apoyo hacia una tutoría verdaderamente personalizada e inteligente.
- **2026-04-10** 📄 Nuestro artículo ya está en arXiv — lee el [preprint](https://arxiv.org/abs/2604.26962) para conocer el diseño y las ideas detrás de DeepTutor.
- **2026-02-06** 🚀 ¡10k estrellas en solo 39 días! Un enorme agradecimiento a nuestra increíble comunidad.
- **2026-01-01** 🎊 ¡Feliz Año Nuevo! Únete a nuestro [Discord](https://discord.gg/eRsjPgMU4t), [WeChat](https://github.com/HKUDS/DeepTutor/issues/78) o [Discussions](https://github.com/HKUDS/DeepTutor/discussions) — juntos demos forma al futuro de DeepTutor.
- **2025-12-29** 🎓 ¡DeepTutor está oficialmente lanzado!
## ✨ Características Principales
DeepTutor es un espacio de trabajo de aprendizaje nativo de agentes que conecta tutoría, resolución de problemas, generación de cuestionarios, investigación, visualización y práctica de dominio en un sistema extensible.
- **Un runtime para todos los modos** — Chat, Quiz, Research, Visualize, Solve y Mastery Path corren en el mismo bucle de agente, de modo que cambias el objetivo, no el motor, y el contexto acompaña al estudiante.
- **Contexto de aprendizaje conectado** — Bases de conocimiento, libros, borradores de Co-Writer, cuadernos, bancos de preguntas, personas y Memory están disponibles en todos los flujos de trabajo en lugar de vivir en herramientas aisladas.
- **Subagentes y Partners** — consulta un Claude Code, Codex o Partner en vivo desde cualquier turno (o importa sus conversaciones pasadas), y ejecuta compañeros IM persistentes con el mismo cerebro.
- **Conocimiento multi-motor** — bibliotecas RAG con versiones: LlamaIndex, PageIndex, GraphRAG, LightRAG o un vault Obsidian vinculado, con análisis de documentos conectable.
- **Herramientas y habilidades extensibles** — herramientas integradas, servidores MCP, modelos de generación de imagen / video / voz, y skills de la comunidad instalables desde EduHub.
- **Memoria inspectable** — trazas L1, resúmenes de superficie L2 y síntesis L3 hacen visible y editable la personalización, con un Memory Graph que traza cada afirmación hasta su evidencia.
---
## 🚀 Comenzar
DeepTutor incluye cuatro rutas de instalación. Todas comparten un diseño de espacio de trabajo: la configuración vive en `data/user/settings/` bajo el directorio desde el que se inicia (o bajo `DEEPTUTOR_HOME` / `deeptutor start --home` si se establece explícitamente). Para la aplicación completa, el flujo recomendado es **elegir un directorio de espacio de trabajo → instalar → `deeptutor init` → `deeptutor start`**.
<details>
<summary><b>Opción 1 — Instalar desde PyPI</b> · aplicación web local completa + CLI, sin necesidad de clonar</summary>
Aplicación web local completa + CLI, sin necesidad de clonar. Requiere **Python 3.11+** y un runtime **Node.js 20+** en PATH (el servidor standalone Next.js empaquetado es iniciado por `deeptutor start`).
```bash
mkdir -p my-deeptutor && cd my-deeptutor
pip install -U deeptutor
deeptutor init # solicita puertos + proveedor LLM + embedding opcional
deeptutor start # inicia backend + frontend; mantener la terminal abierta
```
`deeptutor init` solicita el puerto de backend (predeterminado `8001`), el puerto de frontend (predeterminado `3782`), proveedor LLM / URL base / clave API / modelo y un proveedor de embeddings opcional para Base de Conocimiento / RAG.
Después de `deeptutor start`, abre la URL del frontend impresa en la terminal — por defecto [http://127.0.0.1:3782](http://127.0.0.1:3782). Presiona `Ctrl+C` en esa terminal para detener tanto el backend como el frontend. Omitir `deeptutor init` está bien para una prueba rápida; la aplicación arranca con puertos predeterminados y configuración de modelo vacía, configúralos luego en **Settings → Models**.
</details>
<details>
<summary><b>Opción 2 — Instalar desde el Código Fuente</b> · desarrollar contra un checkout</summary>
Para desarrollo en un checkout. Usa **Python 3.11+** y **Node.js 22 LTS** para coincidir con CI y Docker.
```bash
git clone https://github.com/HKUDS/DeepTutor.git
cd DeepTutor
# Crear un venv (macOS/Linux). Windows PowerShell:
# py -3.11 -m venv .venv ; .\.venv\Scripts\Activate.ps1
python3 -m venv .venv && source .venv/bin/activate
python -m pip install --upgrade pip
# Instalar dependencias de backend + frontend
python -m pip install -e .
( cd web && npm ci --legacy-peer-deps )
deeptutor init
deeptutor start
```
Las instalaciones desde fuente ejecutan Next.js en modo de desarrollo contra el directorio `web/` local; todo lo demás (diseño de configuración, puertos, detener con `Ctrl+C`) coincide con la Opción 1.
<details>
<summary><b>Entorno Conda</b> (en lugar de <code>venv</code>)</summary>
```bash
conda create -n deeptutor python=3.11
conda activate deeptutor
python -m pip install --upgrade pip
```
</details>
<details>
<summary><b>Extras de instalación opcionales</b> — dev / partners / matrix / math-animator</summary>
```bash
pip install -e ".[dev]" # herramientas de pruebas/lint
pip install -e ".[partners]" # SDKs de canales IM de Partners + cliente MCP
pip install -e ".[matrix]" # canal Matrix sin E2EE/libolm
pip install -e ".[matrix-e2e]" # Matrix E2EE; requiere libolm
pip install -e ".[math-animator]" # complemento Manim; requiere LaTeX/ffmpeg/libs del sistema
```
</details>
<details>
<summary><b>Ajustes de dependencias del frontend y solución de problemas del servidor de desarrollo</b></summary>
**Cambiar dependencias del frontend:** ejecuta `npm install --legacy-peer-deps` para actualizar `web/package-lock.json`, luego confirma tanto `web/package.json` como `web/package-lock.json`.
**Servidor de desarrollo atascado:** si `deeptutor start` informa de un frontend existente que no responde, detén el PID que imprime. Si no hay ningún proceso Next.js en ejecución, los archivos de bloqueo están obsoletos — elimínalos y vuelve a intentarlo:
```bash
rm -f web/.next/dev/lock web/.next/lock
deeptutor start
```
</details>
</details>
<details>
<summary><b>Opción 3 — Docker</b> · un contenedor autocontenido</summary>
Un contenedor para la aplicación web completa. Imágenes en GitHub Container Registry:
- `ghcr.io/hkuds/deeptutor:latest` — versión estable
- `ghcr.io/hkuds/deeptutor:pre` — versión preliminar, cuando esté disponible
> Consulta [CONTAINERIZATION.md](../../CONTAINERIZATION.md) para despliegues con podman/rootless/sistema de archivos raíz de solo lectura y la guía completa por instalación.
```bash
docker run --rm --name deeptutor \
-p 127.0.0.1:3782:3782 \
-v deeptutor-data:/app/data \
ghcr.io/hkuds/deeptutor:latest
```
> **Solo se necesita publicar `3782`.** El navegador habla exclusivamente con el origen del frontend; el middleware de Next.js (`web/proxy.ts`) reenvía `/api/*` y `/ws/*` al backend FastAPI **dentro del contenedor**. Publicar `8001` (`-p 127.0.0.1:8001:8001`) es opcional — útil solo para acceder a la API directamente con curl o scripts.
Abre [http://127.0.0.1:3782](http://127.0.0.1:3782). El contenedor crea `/app/data/user/settings/*.json` en el primer arranque; configura los proveedores de modelos desde la página de Settings web. La configuración, las claves API, los registros, los archivos del espacio de trabajo, la memoria y las bases de conocimiento persisten en el volumen `deeptutor-data`.
- **Puertos de host diferentes:** cambia el lado izquierdo de cada mapeo `-p host:container` (ej. `-p 127.0.0.1:8088:3782`). Si cambias los puertos del lado del contenedor en `/app/data/user/settings/system.json`, reinicia y actualiza el lado derecho de cada mapeo para que coincida.
- **Desconectado:** agrega `-d`, luego `docker logs -f deeptutor` para seguir, `docker stop deeptutor` para detener, `docker rm deeptutor` antes de reutilizar el nombre. El volumen `deeptutor-data` mantiene tu configuración y espacio de trabajo entre reinicios.
**Docker remoto / proxy inverso:** el navegador solo habla con el origen del frontend (`:3782`); el middleware de Next.js dentro del contenedor reenvía `/api/*` y `/ws/*` al servidor backend del lado del servidor. Para el caso común de contenedor único no necesitas configurar ninguna base de API — simplemente apunta tu proxy inverso / terminador TLS a `:3782`. Solo necesitas una base de API para un **despliegue dividido** (backend en un contenedor/host separado): establece `next_public_api_base` en `data/user/settings/system.json` con la dirección en red que el servidor frontend usa para llegar al backend (se lee del lado del servidor, nunca se envía al navegador).
```json
{
"next_public_api_base": "http://backend:8001"
}
```
`next_public_api_base_external` (y su alias `public_api_base`) se aceptan como alternativas de menor precedencia. CORS usa **orígenes** de frontend, no URLs de API. Con la autenticación deshabilitada, DeepTutor permite los orígenes normales de navegador HTTP/HTTPS por defecto. Con la autenticación habilitada, agrega los orígenes exactos del frontend:
```json
{
"cors_origins": ["https://deeptutor.example.com"]
}
```
<details>
<summary><b>Conectarse a Ollama / LM Studio / llama.cpp / vLLM / Lemonade en el host</b></summary>
Dentro de Docker, `localhost` es el propio contenedor, no tu máquina host. Para llegar a un servicio de modelo que se ejecuta en el host, usa la puerta de enlace del host (recomendado):
```bash
docker run --rm --name deeptutor \
-p 127.0.0.1:3782:3782 -p 127.0.0.1:8001:8001 \
--add-host=host.docker.internal:host-gateway \
-v deeptutor-data:/app/data \
ghcr.io/hkuds/deeptutor:latest
```
Luego en **Settings → Models**, apunta la URL Base del proveedor a `host.docker.internal`:
- Ollama LLM: `http://host.docker.internal:11434/v1`
- Ollama embedding: `http://host.docker.internal:11434/api/embed`
- LM Studio: `http://host.docker.internal:1234/v1`
- llama.cpp: `http://host.docker.internal:8080/v1`
- Lemonade: `http://host.docker.internal:13305/api/v1`
Docker Desktop (macOS/Windows) generalmente resuelve `host.docker.internal` sin `--add-host`. En Linux, el flag es la forma portátil de crear ese nombre de host en Docker Engine moderno.
**Alternativa para Linux — red del host:** agrega `--network=host` y elimina los flags `-p`. El contenedor comparte la red del host directamente, así que abre [http://127.0.0.1:3782](http://127.0.0.1:3782) (o el `frontend_port` en `system.json`), y los servicios del host se pueden alcanzar con URLs de localhost normales como `http://127.0.0.1:11434/v1`. Ten en cuenta que la red del host expone los puertos del contenedor directamente en el host y puede entrar en conflicto con servicios existentes — para mantenerlos en loopback, establece `BACKEND_HOST=127.0.0.1` y `FRONTEND_HOST=127.0.0.1` (consulta [CONTAINERIZATION.md](../../CONTAINERIZATION.md)).
</details>
</details>
<details>
<summary><b>Opción 4 — Solo CLI</b> · sin UI web, desde un checkout de fuente</summary>
Cuando no necesitas la UI web. El paquete de solo CLI se instala desde un checkout de fuente, no desde PyPI.
```bash
git clone https://github.com/HKUDS/DeepTutor.git
cd DeepTutor
# Crear un venv (macOS/Linux). Windows PowerShell:
# py -3.11 -m venv .venv-cli ; .\.venv-cli\Scripts\Activate.ps1
python3 -m venv .venv-cli && source .venv-cli/bin/activate
python -m pip install --upgrade pip
python -m pip install -e ./packaging/deeptutor-cli
deeptutor init --cli
deeptutor chat
```
`deeptutor init --cli` comparte el mismo diseño `data/user/settings/` que la aplicación completa pero omite las solicitudes de puertos de backend/frontend y establece embeddings en **desactivado** (elige `Yes` si planeas usar `deeptutor kb …` o herramientas RAG). Aún escribe un diseño de runtime completo (`system.json`, `auth.json`, `integrations.json`, `model_catalog.json`, `main.yaml`, `agents.yaml`) y aún solicita el proveedor LLM y modelo activos.
<details>
<summary><b>Comandos comunes</b></summary>
```bash
deeptutor chat # REPL interactivo
deeptutor chat --capability deep_solve --tool rag --kb my-kb
deeptutor run chat "Explain Fourier transform"
deeptutor run deep_solve "Solve x^2 = 4" --tool rag --kb my-kb
deeptutor kb create my-kb --doc textbook.pdf
deeptutor memory show
deeptutor config show
```
</details>
La instalación local de `deeptutor-cli` no incluye activos web ni dependencias de servidor. Mantén el checkout de fuente cerca — la instalación editable apunta a él. Para agregar la aplicación web más tarde, instala el paquete PyPI (Opción 1) y ejecuta `deeptutor init` + `deeptutor start` desde el mismo espacio de trabajo.
</details>
<details>
<summary><b>Sandbox de Ejecución de Código (skills de oficina)</b> · ejecutar código generado por el modelo para docx / pdf / pptx / xlsx</summary>
Las skills de oficina integradas — **docx / pdf / pptx / xlsx** — funcionan haciendo que el
modelo escriba un script Python corto (`python-docx`, `reportlab`, `openpyxl`, …),
lo ejecute a través de las herramientas `exec` / `code_execution` y devuelva una URL de descarga.
Esas herramientas se montan siempre que un backend de sandbox esté activo, lo cual ocurre **por defecto**
en cada forma de despliegue:
- **Local (Opción 1 / 2) y Docker (Opción 3, contenedor único):** un sandbox de subproceso restringido
ejecuta el código del modelo (localmente en el host, o dentro del contenedor bajo Docker — el contenedor
siendo su propio límite de aislamiento).
- **docker-compose:** enrutado en su lugar a un **sidecar runner** endurecido y con privilegios mínimos
(`Dockerfile.runner`) a través de `DEEPTUTOR_SANDBOX_RUNNER_URL` — la postura más sólida, y preferida
automáticamente cuando está presente.
El sandbox de subproceso está controlado por la configuración `sandbox_allow_subprocess` en
`data/user/settings/system.json` (predeterminado `true`). Ejecutar código generado por el modelo en tu
host es una decisión real de confianza — establécelo en `false` (o exporta
`DEEPTUTOR_SANDBOX_ALLOW_SUBPROCESS=0`) para deshabilitar la ejecución del lado del host, a costa de
que las skills de oficina ya no puedan producir archivos.
</details>
<details>
<summary><b>Referencia de configuración</b> — archivos de configuración bajo <code>data/user/settings/</code> (JSON/YAML)</summary>
Todo bajo `data/user/settings/` es JSON/YAML plano. La página **Settings** en el navegador es el editor recomendado.
| Archivo | Propósito |
|:---|:---|
| `model_catalog.json` | Perfiles de proveedores LLM, embeddings y búsqueda; claves API; modelos activos |
| `system.json` | Puertos de backend/frontend, base de API pública, CORS, verificación SSL, directorio de adjuntos |
| `auth.json` | Interruptor de autenticación opcional, nombre de usuario, hash de contraseña, configuración de token/cookie |
| `integrations.json` | Configuración opcional de PocketBase e integraciones sidecar |
| `interface.json` | Preferencias de idioma / tema / barra lateral de UI |
| `main.yaml` | Valores predeterminados de comportamiento de runtime e inyección de rutas |
| `agents.yaml` | Configuración de temperatura y tokens de capacidades/herramientas |
El `.env` de la raíz del proyecto **no** se lee como archivo de configuración de la aplicación. Para una configuración mínima del modelo, abre **Settings → Models**, agrega un perfil LLM (URL Base / clave API / nombre del modelo) y guarda. Agrega un perfil de embeddings solo si planeas usar funciones de Base de Conocimiento / RAG.
</details>
## 📖 Explorar DeepTutor
Comienza con las superficies principales que usarás día a día: Chat, Partners, Mis Agentes, Co-Writer, Book, Centro de Conocimiento, Espacio de Aprendizaje, Memory y Settings. El tour luego cubre los despliegues Multi-Usuario para espacios de trabajo compartidos y aislados.
<div align="center">
<img src="../../assets/figs/web-1.4.6+/OVERVIEW.png" alt="Inicio de DeepTutor — el espacio de trabajo Chat con todas las superficies en la barra lateral" width="900">
</div>
<details>
<summary><b>🏗️ Arquitectura del sistema</b></summary>
<div align="center">
<img src="../../assets/figs/system/system%20architecture.png" alt="Arquitectura del sistema DeepTutor" width="900">
</div>
</details>
<details>
<summary><b>💬 Chat — El Bucle de Agente que Realmente Usas</b></summary>
Chat es la capacidad predeterminada y el lugar donde comienza la mayor parte del trabajo. Un único hilo puede conversar normalmente, llamar herramientas, fundamentarse en bases de conocimiento seleccionadas, leer adjuntos, generar imágenes, consultar subagentes, escribir registros de notebook y continuar con el mismo contexto entre turnos.
<div align="center">
<img src="../../assets/figs/web-1.4.6+/home/00-overview.png" alt="Espacio de trabajo de chat DeepTutor" width="900">
</div>
El bucle es deliberadamente simple: el modelo piensa en rondas, llama herramientas cuando es útil, observa los resultados y termina con un mensaje sin herramientas. `ask_user` es especial — en lugar de adivinar, el agente puede pausar el turno, hacer una pregunta de aclaración estructurada y reanudar una vez que respondes.
<div align="center">
<img src="../../assets/figs/system/chat-agent-loop.png" alt="Bucle de agente de chat DeepTutor" width="900">
</div>
Las herramientas activables por el usuario son `brainstorm`, `web_search`, `paper_search`, `reason` y `geogebra_analysis` — más `imagegen` y `videogen` una vez que configures el modelo de generación correspondiente. Las herramientas contextuales como `rag`, `read_source`, `read_memory`, `write_memory`, `read_skill`, `load_tools`, `exec`, `web_fetch`, `ask_user`, `list_notebook`, `write_note`, `github` y `consult_subagent` se montan automáticamente cuando el turno tiene el contexto adecuado.
El contexto viene en dos tipos: el **contexto de sesión persistente** (subagente, bases de conocimiento, persona, modelo, voz) vive en la barra de herramientas del compositor y persiste entre turnos; las **referencias de un solo uso** (archivos, historial de chat, libros, cuadernos, banco de preguntas, agentes importados) vienen del menú `+` para un único turno.
Chat es también el punto de lanzamiento para capacidades más profundas: **Quiz** para generación de preguntas, **Research** para informes con citas, **Visualize** para gráficos / diagramas / animaciones, y — bajo *More Capabilities***Solve** para razonamiento trabajado y **Mastery Path** para flujos de planes de aprendizaje.
</details>
<details>
<summary><b>🤝 Partner — Compañeros Persistentes con el Mismo Cerebro</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/partners/00-partners%20overview.png" alt="Espacio de trabajo de partners DeepTutor" width="900">
</div>
Los Partners son compañeros persistentes con su propio alma, política de modelo, biblioteca, memoria y canales. No son un motor de bot separado: cada mensaje web o IM entrante se convierte en un turno normal de `ChatOrchestrator` dentro de un espacio de trabajo con alcance de partner. Un partner es "un chat que tiene personalidad y número de teléfono."
<div align="center">
<img src="../../assets/figs/system/partners-architecture.png" alt="Arquitectura de partners DeepTutor" width="900">
</div>
Cada partner tiene un `SOUL.md`, selección de modelo, canales, política de herramientas y biblioteca asignada. Las bases de conocimiento, skills y notebooks se copian en `data/partners/<id>/workspace/`, por lo que las mismas herramientas de RAG, skill, notebook y memoria funcionan sin casos especiales. Un partner lee la memoria de su propietario pero solo escribe en la suya propia.
<div align="center">
<img src="../../assets/figs/web-1.4.6+/partners/02-IM%20config%20for%20each%20partner.png" alt="Configuración de canales IM por partner" width="900">
</div>
La capa de canales está impulsada por esquema y puede conectarse a plataformas IM como Feishu, Telegram, Slack, Discord, DingTalk, QQ/NapCat, WeCom, WhatsApp, Zulip, Mattermost, Matrix, Mochat y Microsoft Teams dependiendo de los extras instalados y las credenciales configuradas. Un partner también puede conectarse como subagente y ser consultado desde un turno de chat normal — consulta **Mis Agentes** a continuación.
</details>
<details>
<summary><b>🧑‍🚀 Mis Agentes — Consultar e Importar Otros Agentes</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/myagents/00-overview.png" alt="Espacio de trabajo de Mis Agentes DeepTutor" width="900">
</div>
Mis Agentes convierte a otros agentes en contexto para DeepTutor y hace dos cosas distintas. **Conectar un agente en vivo** — un Claude Code o Codex CLI en tu máquina, o uno de tus Partners — y consultarlo desde dentro de un turno de chat: DeepTutor realmente *ejecuta* el otro agente y transmite su trabajo al panel de Activity a través de la herramienta `consult_subagent`. Selecciónalo con el chip de Agente (o escribe `@`), y establece cuántas rondas puede tomar la consulta.
<div align="center">
<img src="../../assets/figs/web-1.4.6+/home/08-subagent%20demo%20with%20claude%20code.png" alt="Consultando un subagente Claude Code en vivo" width="900">
</div>
**Importar conversaciones pasadas** — trae tu historial existente de Claude Code y Codex como agentes nombrados, buscables y reanudables. Elige qué días importar; actualizar los vuelve a sincronizar. Referencia una conversación importada desde cualquier turno de chat a través de `+` → Mis Agentes, y DeepTutor la lee como un transcript de terceros — sigue siendo *su* conversación, no la voz propia de DeepTutor.
</details>
<details>
<summary><b>✍️ Co-Writer — Redacción Markdown con Conciencia de Selección</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/co-writer/00-overview.png" alt="Espacio de trabajo Co-Writer DeepTutor" width="900">
</div>
Co-Writer es un espacio de trabajo Markdown de vista dividida para informes, tutoriales, notas y artefactos de aprendizaje de formato largo. Los documentos se guardan automáticamente y renderizan una vista previa en vivo (matemáticas KaTeX, cercas de diagramas), y se pueden guardar de vuelta en cuadernos cuando un borrador se convierte en contexto reutilizable.
<div align="center">
<img src="../../assets/figs/web-1.4.6+/co-writer/01-edit%20panel.png" alt="Editor Co-Writer con vista previa en vivo" width="900">
</div>
Su idea definitoria es la **edición quirúrgica**: selecciona un fragmento y pide a DeepTutor que lo reescriba, expanda o acorte. El agente de edición puede fundamentar el cambio en una base de conocimiento o evidencia web, mantiene un rastro de sus llamadas a herramientas y muestra cada cambio como un diff de aceptar/rechazar — de modo que nada se aplica hasta que lo apruebes.
</details>
<details>
<summary><b>📖 Book — Libros Vivos de tus Materiales</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/book/00-book_overview.png" alt="Biblioteca de libros DeepTutor" width="900">
</div>
Book convierte las fuentes seleccionadas en un **libro vivo** interactivo — no un PDF estático, sino un entorno de lectura construido a partir de bloques tipados. Un libro puede comenzar desde bases de conocimiento, cuadernos, bancos de preguntas o historial de chat; el flujo de creación propone un esquema de capítulos antes de que se genere el contenido, así revisas la estructura en lugar de aceptar una salida de un solo intento sin verla antes.
<p align="center">
<img src="../../assets/figs/web-1.4.6+/book/01-book-demo-quiz%20card.png" alt="Bloque de quiz en Book" width="31%">
&nbsp;
<img src="../../assets/figs/web-1.4.6+/book/02-book-demo-manim%20video.png" alt="Bloque de animación Manim en Book" width="31%">
&nbsp;
<img src="../../assets/figs/web-1.4.6+/book/03-book-demo%20interactive%20module.png" alt="Bloque de widget interactivo en Book" width="31%">
</p>
Cada capítulo se compila en bloques tipados — texto, callouts, quizzes, tarjetas flash, líneas de tiempo, código, figuras, HTML interactivo, animaciones, gráficos de conceptos, profundizaciones y notas de usuario — y cada página tiene su propio Page Chat. Los bloques son editables: inserta, mueve, regenera o cambia el tipo de un bloque sin reescribir el capítulo. Los comandos de mantenimiento como `deeptutor book health` y `deeptutor book refresh-fingerprints` ayudan a detectar cuándo el conocimiento fuente ha divergido de las páginas compiladas.
</details>
<details>
<summary><b>📚 Centro de Conocimiento — Bibliotecas RAG Multi-Motor</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/knowledge/00-overview.png" alt="Centro de Conocimiento DeepTutor" width="900">
</div>
Las bases de conocimiento son las colecciones de documentos detrás del RAG — fundamentan los turnos de Chat, las ediciones de Co-Writer, la generación de Book y las conversaciones de Partner. Lo que las distingue es la **elección de motores de recuperación**: **LlamaIndex** (el predeterminado, vector local + BM25), **PageIndex** (hospedado, recuperación por razonamiento con citas a nivel de página), **GraphRAG** y **LightRAG** (recuperación por grafo de conocimiento), **LightRAG Server** (recuperación delegada a una instancia externa de LightRAG a la que te conectas por HTTP), o un vault **Obsidian** vinculado que el tutor lee y escribe en el lugar. Cada KB está vinculada a un motor.
<div align="center">
<img src="../../assets/figs/web-1.4.6+/knowledge/01-create%20knowledge%20base.png" alt="Crear una base de conocimiento" width="900">
</div>
Al crear una KB, puedes **crear nueva** (subir documentos y construir un índice nuevo) o **vincular existente** (reutilizar un índice construido en otro lugar, leer en el lugar sin re-indexar). La re-indexación escribe un nuevo directorio `version-N` plano y conserva los anteriores, de modo que un índice funcional nunca se destruye a mitad de la reconstrucción. Un solo documento puede eliminarse incluso de una base en estado de **error** — descartando un archivo que no se pudo analizar sin necesidad de borrar y reconstruir todo. El análisis de documentos — Text-only, MinerU, Docling, markitdown o PyMuPDF4LLM — se elige en **Settings → Knowledge Base**, con descargas de modelos locales desactivadas por defecto. La CLI refleja el ciclo de vida con `deeptutor kb list`, `info`, `create`, `add`, `search`, `set-default` y `delete`.
</details>
<details>
<summary><b>🌐 Espacio de Aprendizaje — Skills, Personas y Contexto Reutilizable</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/learning-space/00-overview.png" alt="Hub del Espacio de Aprendizaje DeepTutor" width="900">
</div>
El Espacio de Aprendizaje es la capa de biblioteca y personalización — donde viven las cosas que persisten. **Conversaciones y Materiales** guarda tu historial de chat, cuadernos y un banco de preguntas (cada pregunta guardada conserva tu respuesta, la respuesta de referencia y una explicación). **Personalización** guarda rutas de dominio, personas (preajustes de comportamiento como *compañero*, *asistente de investigación*, *profesor*) y skills (guías `SKILL.md` que el modelo lee bajo demanda). Todo aquí se puede reutilizar desde Chat, Partners, Co-Writer y Book.
<div align="center">
<img src="../../assets/figs/web-1.4.6+/learning-space/07-%20download%20skills%20from%20eduhub.png" alt="Importar skills desde EduHub" width="900">
</div>
No tienes que escribir cada skill tú mismo — **Importar desde EduHub** navega el catálogo comunitario y descarga una skill directamente en tu biblioteca a través de una puerta de seguridad (consulta [Ecosistema](#-ecosistema--eduhub-y-la-comunidad-de-skills)).
</details>
<details>
<summary><b>🧠 Memory — Personalización Inspectable</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/memory/00-overview.png" alt="Vista general de Memory DeepTutor" width="900">
</div>
Memory es un sistema de tres capas respaldado por archivos que puedes leer, curar y auditar — deliberadamente *no* un almacén de vectores oculto. **L1** es el espejo del espacio de trabajo más un rastro de eventos de solo adición (`trace/<surface>/<date>.jsonl`); **L2** son hechos curados por superficie (`L2/<surface>.md`); **L3** es síntesis entre superficies (`L3/<profile|recent|scope|preferences>.md`). Como L2 cita a L1 y L3 cita a L2, nada en tu perfil queda sin rendir cuentas.
<div align="center">
<img src="../../assets/figs/web-1.4.6+/memory/01-3%20layer%20memory%20graph.png" alt="Gráfico de memoria DeepTutor" width="900">
</div>
El Memory Graph muestra toda la pirámide — síntesis L3 en el centro, L2 en el anillo intermedio, trazas L1 en el exterior — de modo que puedes rastrear cualquier afirmación sintetizada hasta el evento bruto exacto detrás de ella. La memoria se rastrea en las superficies `chat`, `notebook`, `quiz`, `kb`, `book`, partner y `cowriter`; los presupuestos de Actualización / Auditoría / Deduplicación del consolidador se ajustan en **Settings → Memory**.
</details>
<details>
<summary><b>⚙️ Settings — Un Panel de Control</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/settings/00-setting%20overview.png" alt="Hub de configuración DeepTutor" width="900">
</div>
Settings es el panel de control operativo, con una tira de estado en vivo (Backend, LLM, Embedding, Search) y una tarjeta por área: **Apariencia** (tema + idioma de UI), **Red** (base de API, puertos, CORS), **Modelos** (LLM, Embedding, Search, Text-to-Speech, Speech-to-Text, Image Generation, Video Generation), **Knowledge Base** (motor de análisis de documentos), **Chat** (herramientas, servidores MCP, parámetros por capacidad), **Partners & Agents** (los subagentes que puedes consultar desde un turno), y **Memory** (los presupuestos del consolidador).
<div align="center">
<img src="../../assets/figs/web-1.4.6+/settings/01-appearance%20settings.png" alt="Configuración de apariencia de DeepTutor y temas" width="900">
</div>
La mayoría de las secciones usan un flujo de borrador y aplicación, de modo que puedes probar un proveedor antes de confirmarlo. Cuatro temas se incluyen por defecto — Default, Cream, Dark y Glass. Los archivos `.env` de la raíz del proyecto se ignoran intencionalmente; la configuración de runtime vive bajo `data/user/settings/*.json` a menos que `DEEPTUTOR_HOME` o `deeptutor start --home` apunten la app en otro lugar.
</details>
<details>
<summary><b>👥 Multi-Usuario — Despliegues Compartidos</b> · autenticación opcional, espacios de trabajo aislados por usuario</summary>
La autenticación está **desactivada por defecto** — DeepTutor corre en modo monousuario. Actívala y un árbol `data/` aloja un espacio de trabajo de administrador, espacios de trabajo aislados por usuario y espacios de trabajo de partner en paralelo:
```text
data/
├── user/ # Espacio de trabajo del administrador + configuración global
├── users/<uid>/ # Alcance por usuario: historial de chat, memoria, cuadernos, KBs
├── partners/<id>/workspace/ # Alcance del partner (usuario sintético)
└── system/ # auth/users.json · grants/<uid>.json · audit/usage.jsonl
```
El **primer usuario registrado se convierte en administrador** y es dueño de catálogos de modelos, credenciales de proveedor, bases de conocimiento compartidas, skills y permisos por usuario. Todos los demás obtienen un espacio de trabajo aislado y una página de Settings redactada — los modelos, KBs y skills asignados por el administrador aparecen como opciones con alcance de solo lectura, nunca como claves API en bruto.
**Activarlo:** activa la autenticación en `data/user/settings/auth.json`, reinicia `deeptutor start`, registra al primer administrador en `/register`, luego agrega usuarios desde `/admin/users` y asigna modelos, KBs, skills, Partners, política de herramientas/MCP y acceso de ejecución de código a través de permisos.
> PocketBase sigue siendo una integración monousuario — mantén `integrations.pocketbase_url` en blanco para despliegues multi-usuario a menos que hayas conectado un almacén de usuarios externo.
</details>
## ⌨️ DeepTutor CLI — Interfaz Nativa de Agentes
Un binario `deeptutor`, dos formas de entrar: un **REPL** interactivo para quienes viven en la terminal, y **JSON** estructurado para otros agentes que manejan DeepTutor como herramienta. Las mismas capacidades, herramientas y bases de conocimiento de cualquier manera.
<details>
<summary><b>Manejarlo tú mismo</b></summary>
`deeptutor chat` abre un REPL interactivo; `deeptutor run <capability> "<message>"` ejecuta un único turno y sale. Ambos comparten los mismos flags `--capability`, `--tool`, `--kb` y `--config`.
```bash
deeptutor chat # REPL interactivo
deeptutor chat --capability deep_solve --kb my-kb --tool rag
deeptutor run chat "Explain the Fourier transform" --tool rag --kb textbook
deeptutor run deep_research "Survey 2026 papers on RAG" \
--config mode=report --config depth=standard
```
Todo lo que hace la aplicación Web también está aquí — bases de conocimiento (`kb`), sesiones (`session`), partners (`partner`), skills (`skill`), cuadernos, memoria y config. Lista completa a continuación.
</details>
<details>
<summary><b>Dejar que un agente lo maneje</b></summary>
DeepTutor está construido para ser *operado por otro agente*. Agrega `--format json` a cualquier `run` y cada turno transmite **NDJSON — un evento por línea** (`content`, `tool_call`, `tool_result`, `done`, …), cada línea etiquetada con su `session_id`. Las ejecuciones son seguras sin TTY: una pausa `ask_user` sin TTY se resuelve automáticamente con una respuesta vacía en lugar de bloquearse.
```bash
# Disparo único, legible por máquina
deeptutor run deep_solve "Find d/dx[sin(x^2)]" --tool reason --format json
# Encadenar turnos en una sesión con estado — captura el id, reutilízalo
SID=$(deeptutor run deep_research "Survey 2026 papers on RAG" \
--config mode=report --config depth=standard --format json \
| jq -r 'select(.type=="done").session_id')
deeptutor run deep_question "Quiz me on that survey" --session "$SID" --format json
```
El repo incluye un [`SKILL.md`](../../SKILL.md) raíz — un documento de traspaso de ~150 líneas que enseña a cualquier LLM que use herramientas toda la superficie en una lectura. Entrégaselo a Claude Code, Codex u OpenCode (los recogen automáticamente), o envuelve `deeptutor run` como herramienta en un bucle LangChain / AutoGen. Recetas completas: [Agent Handoff](https://deeptutor.info/docs/cli/agent-handoff/).
</details>
<details>
<summary><b>Referencia de comandos</b></summary>
| Comando | Descripción |
|:---|:---|
| `deeptutor init` | Crear o actualizar `data/user/settings` para el espacio de trabajo actual |
| `deeptutor start [--home PATH]` | Lanzar backend + frontend juntos |
| `deeptutor serve [--port PORT]` | Iniciar solo el backend FastAPI |
| `deeptutor run <capability> <message>` | Ejecutar un turno de capacidad único (`chat`, `deep_solve`, `deep_question`, `deep_research`, `visualize`, `math_animator`, `mastery_path`); agrega `--format json` para salida NDJSON |
| `deeptutor chat` | REPL interactivo con controles de capacidad, herramienta, KB, notebook e historial |
| `deeptutor partner list/create/start/stop` | Gestionar partners conectados por IM |
| `deeptutor kb list/info/create/add/search/set-default/delete` | Gestionar bases de conocimiento LlamaIndex |
| `deeptutor skill search/install/list/remove/login/logout/publish/update` | Gestionar skills, instalar desde hubs y publicar las propias (`eduhub:<slug>` por defecto, consulta Ecosistema) |
| `deeptutor memory show/clear` | Inspeccionar documentos de memoria L2/L3 o borrar memoria L1/toda |
| `deeptutor session list/show/open/rename/delete` | Gestionar sesiones compartidas |
| `deeptutor notebook list/create/show/add-md/replace-md/remove-record` | Gestionar cuadernos desde archivos Markdown |
| `deeptutor book list/health/refresh-fingerprints` | Inspeccionar libros y actualizar huellas dactilares de fuentes |
| `deeptutor plugin list/info` | Inspeccionar herramientas y capacidades registradas |
| `deeptutor config show` | Imprimir resumen de configuración |
| `deeptutor provider login <provider>` | Autenticación del proveedor (`openai-codex` OAuth login; `github-copilot` valida una sesión de autenticación Copilot existente) |
</details>
<details>
<summary><b>Distribución de solo CLI</b></summary>
El paquete de solo CLI vive en `packaging/deeptutor-cli`. En este checkout, instálalo desde fuente:
```bash
python -m pip install -e ./packaging/deeptutor-cli
```
Aún no está publicado en PyPI, así que la sección principal de [Comenzar](#-comenzar) mantiene la ruta de instalación desde fuente.
</details>
## 🧩 Ecosistema — EduHub y la Comunidad de Skills
Las skills de DeepTutor usan el formato abierto **Agent-Skills** — una carpeta con una guía `SKILL.md` (frontmatter YAML + Markdown) y archivos de referencia opcionales. No hay nada específico de DeepTutor en ello, así que cualquier registro que hable el formato se convierte en una fuente para tu biblioteca. DeepTutor incluye **[EduHub](https://eduhub.deeptutor.info/)** — nuestro propio registro de skills enfocado en educación — conectado como hub predeterminado.
<details>
<summary><b>EduHub — el ecosistema de skills de DeepTutor</b></summary>
[**EduHub**](https://eduhub.deeptutor.info/) es el hub comunitario que DeepTutor lanzó para compartir skills de agentes orientadas a la enseñanza — tutores socráticos, constructores de tarjetas flash, retroalimentación de ensayos, planos de examen, explicadores de conceptos y más. Está integrado en DeepTutor, así que no hay nada que configurar: un slug simple o un prefijo `eduhub:` se resuelve a él.
**Encontrar e instalar** — en el navegador, abre **Learning Space → Skills → Import from EduHub** para navegar el catálogo y descargar una skill directamente en tu biblioteca. Desde la terminal:
```bash
deeptutor skill search "socratic tutor" # buscar en EduHub (el hub predeterminado)
deeptutor skill install socratic-tutor # fetch → verificar → registrar
deeptutor skill install eduhub:socratic-tutor@1.2.0 # fijar un hub y una versión
deeptutor skill list # skills locales con su proveniencia del hub
```
**Publicar la tuya propia** — empaqueta un `SKILL.md` y compártelo con la comunidad:
```bash
deeptutor skill login # inicio de sesión en EduHub desde el navegador
deeptutor skill publish ./my-skill # interactivo: elige una pista + etiquetas, luego sube
deeptutor skill update # revertir o lanzar una nueva versión
```
EduHub también es un registro independiente compatible con ClawHub, así que los agentes que no son DeepTutor (Claude Code, Codex, …) pueden usarlo directamente a través del CLI `eduhub``npx eduhub install socratic-tutor`.
</details>
<details>
<summary><b>La puerta de seguridad de importación</b></summary>
Sea cual sea la fuente, cada importación pasa la **misma puerta de seguridad** antes de que nada toque tu espacio de trabajo:
- el **veredicto de seguridad** del registro se verifica primero — los paquetes marcados se rechazan a menos que pases `--allow-unverified`;
- los archivos se extraen defensivamente (guardas contra zip-slip / zip-bomb) detrás de una **lista blanca de sufijos** de texto/script, de modo que los binarios nunca aterrizan en el espacio de trabajo;
- el frontmatter se normaliza al esquema de DeepTutor y `always:` se **elimina**, de modo que una skill descargada nunca puede forzarse en cada prompt del sistema;
- la proveniencia — hub, versión, veredicto y tiempo de instalación — se escribe en `.hub-lock.json` para auditorías y actualizaciones.
En despliegues multi-usuario, la instalación es solo para administradores: una nueva skill aterriza en el catálogo del administrador y permanece invisible para otros usuarios hasta que un permiso la asigne, de modo que un administrador puede verificarla antes de distribuirla.
</details>
<details>
<summary><b>También compatible con ClawHub</b></summary>
Como DeepTutor habla el formato abierto Agent-Skills, **[ClawHub](https://clawhub.ai/)** también funciona como fuente de primera clase — está integrado junto con EduHub. Selecciónalo con el prefijo del hub:
```bash
deeptutor skill search "git release notes" --hub clawhub
deeptutor skill install clawhub:git-release-notes@1.0.1
```
Agrega más registros en `settings/skill_hubs.json`: una entrada `type: "clawhub"` apunta a cualquier API HTTP compatible (EduHub y ClawHub ambas lo hablan), `type: "command"` envuelve cualquier CLI de fetch que envíe un registro, y `"default"` elige el hub usado para slugs simples. Todos ellos alimentan la misma puerta de importación.
</details>
## 🌐 Comunidad
### 📮 Contacto
DeepTutor es un proyecto de código abierto liderado por [Bingxi Zhao](https://github.com/pancacake) dentro del grupo [HKUDS](https://github.com/HKUDS), y se itera en **forma completamente de código abierto**, construido junto con la comunidad. Hasta ahora, **NO** tenemos productos en línea de pago de ningún tipo. No dudes en contactarnos en **bingxizhao39@gmail.com** para discusiones, ideas o colaboración.
### 🙏 Agradecimientos
Un agradecimiento de corazón a [**Chao Huang**](https://sites.google.com/view/chaoh), director del Data Intelligence Lab @ HKU, y a nuestros compañeros de HKUDS por su cálido apoyo — especialmente [**Jiahao Zhang**](https://github.com/zzhtx258), [**Zirui Guo**](https://github.com/LarFii) y [**Xubin Ren**](https://github.com/Re-bin). También estamos profundamente agradecidos a la **comunidad de código abierto**: tus estrellas, issues, pull requests y discusiones dan forma a DeepTutor todos los días.
DeepTutor también se apoya en los hombros de destacados proyectos de código abierto que nos dieron herramientas e inspiración:
| Proyecto | Rol / Inspiración |
|:---|:---|
| [**LlamaIndex**](https://github.com/run-llama/llama_index) | Columna vertebral del pipeline RAG y la indexación de documentos |
| [**nanobot**](https://github.com/HKUDS/nanobot) | Motor de agente ultraligero que impulsó el TutorBot original *(HKUDS)* |
| [**LightRAG**](https://github.com/HKUDS/LightRAG) | RAG simple y rápido *(HKUDS)* |
| [**AutoAgent**](https://github.com/HKUDS/AutoAgent) | Marco de agentes sin código *(HKUDS)* |
| [**AI-Researcher**](https://github.com/HKUDS/AI-Researcher) | Pipeline de investigación automatizada *(HKUDS)* |
| [**OpenClaw**](https://github.com/openclaw/openclaw) | Pasarela de agentes abierta y ecosistema de skills detrás de ClawHub |
| [**Codex**](https://github.com/openai/codex) | CLI de codificación nativo de agentes que inspiró nuestro flujo de trabajo CLI |
| [**Claude Code**](https://github.com/anthropics/claude-code) | CLI de codificación agéntica que inspiró el bucle de agentes de DeepTutor |
| [**ManimCat**](https://github.com/Wing900/ManimCat) | Generación de animaciones matemáticas impulsada por IA para Math Animator |
### 🗺️ Roadmap y Contribuir
Queremos que DeepTutor siga iterando y mejorando — y en última instancia se convierta en un regalo que devolvamos a la comunidad de código abierto. Nuestro [**roadmap**](https://github.com/HKUDS/DeepTutor/issues/498) se actualiza continuamente; vota en los elementos allí o propone nuevos. Si deseas contribuir, consulta la [**Guía de Contribución**](../../CONTRIBUTING.md) para la estrategia de ramas, estándares de código y cómo comenzar.
<div align="center">
Esperamos que DeepTutor se convierta en un regalo para la comunidad. 🎁
<a href="https://github.com/HKUDS/DeepTutor/graphs/contributors">
<img src="https://contrib.rocks/image?repo=HKUDS/DeepTutor&max=999" alt="Contribuidores" />
</a>
</div>
<div align="center">
<a href="https://www.star-history.com/#HKUDS/DeepTutor&type=timeline&legend=top-left">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=HKUDS/DeepTutor&type=timeline&theme=dark&legend=top-left" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=HKUDS/DeepTutor&type=timeline&legend=top-left" />
<img alt="Gráfico de historial de estrellas" src="https://api.star-history.com/svg?repos=HKUDS/DeepTutor&type=timeline&legend=top-left" />
</picture>
</a>
</div>
<p align="center">
<a href="https://www.star-history.com/hkuds/deeptutor">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/badge?repo=HKUDS/DeepTutor&theme=dark" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/badge?repo=HKUDS/DeepTutor" />
<img alt="Clasificación del historial de estrellas" src="https://api.star-history.com/badge?repo=HKUDS/DeepTutor" />
</picture>
</a>
</p>
<div align="center">
Licenciado bajo [Apache License 2.0](../../LICENSE).
<p>
<img src="https://visitor-badge.laobi.icu/badge?page_id=HKUDS.DeepTutor&style=for-the-badge&color=00d4ff" alt="Vistas">
</p>
</div>
+729
View File
@@ -0,0 +1,729 @@
<div align="center">
<p align="center"><img src="../../assets/figs/logo/logo.png" alt="DeepTutor logo" height="56" style="vertical-align: middle;">&nbsp;<img src="../../assets/figs/logo/banner.png" alt="DeepTutor" height="48" style="vertical-align: middle;"></p>
# DeepTutor : Tutorat Personnalisé à Vie
<p align="center">
<a href="https://deeptutor.info" target="_blank"><img alt="Docs — deeptutor.info" src="https://img.shields.io/badge/Docs-deeptutor.info%20%E2%86%97-0A0A0A?style=for-the-badge&labelColor=F5F5F4" height="36"></a>
</p>
<p align="center">
<a href="https://trendshift.io/repositories/17099?utm_source=repository-badge&amp;utm_medium=badge&amp;utm_campaign=badge-repository-17099" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/repositories/17099" alt="HKUDS%2FDeepTutor | Trendshift" width="250" height="55"/></a>&nbsp;
<a href="https://trendshift.io/repositories/17099?utm_source=trendshift-badge&amp;utm_medium=badge&amp;utm_campaign=badge-trendshift-17099" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/17099/daily" alt="HKUDS%2FDeepTutor | Trendshift" width="250" height="55"/></a>&nbsp;
<a href="https://trendshift.io/repositories/17099?utm_source=trendshift-badge&amp;utm_medium=badge&amp;utm_campaign=badge-trendshift-17099" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/17099/weekly?language=Python" alt="HKUDS%2FDeepTutor | Trendshift" width="250" height="55"/></a>
</p>
<p align="center">
<a href="../../README.md"><img alt="English" height="40" src="https://img.shields.io/badge/English-CDCFD4"></a>&nbsp;
<a href="README_CN.md"><img alt="简体中文" height="40" src="https://img.shields.io/badge/简体中文-CDCFD4"></a>&nbsp;
<a href="README_JA.md"><img alt="日本語" height="40" src="https://img.shields.io/badge/日本語-CDCFD4"></a>&nbsp;
<a href="README_ES.md"><img alt="Español" height="40" src="https://img.shields.io/badge/Español-CDCFD4"></a>&nbsp;
<a href="README_FR.md"><img alt="Français" height="40" src="https://img.shields.io/badge/Français-BCDCF7"></a>&nbsp;
<a href="README_AR.md"><img alt="Arabic" height="40" src="https://img.shields.io/badge/Arabic-CDCFD4"></a>&nbsp;
<a href="README_RU.md"><img alt="Русский" height="40" src="https://img.shields.io/badge/Русский-CDCFD4"></a>&nbsp;
<a href="README_HI.md"><img alt="Hindi" height="40" src="https://img.shields.io/badge/Hindi-CDCFD4"></a>&nbsp;
<a href="README_PT.md"><img alt="Português" height="40" src="https://img.shields.io/badge/Português-CDCFD4"></a>&nbsp;
<a href="README_TH.md"><img alt="Thai" height="40" src="https://img.shields.io/badge/Thai-CDCFD4"></a>&nbsp;
<a href="README_PL.md"><img alt="Polski" height="40" src="https://img.shields.io/badge/Polski-CDCFD4"></a>
</p>
[![Python 3.11+](https://img.shields.io/badge/Python-3.11%2B-3776AB?style=flat-square&logo=python&logoColor=white)](https://www.python.org/downloads/)
[![Next.js 16](https://img.shields.io/badge/Next.js-16-000000?style=flat-square&logo=next.js&logoColor=white)](https://nextjs.org/)
[![License](https://img.shields.io/badge/License-Apache_2.0-blue?style=flat-square)](LICENSE)
[![GitHub release](https://img.shields.io/github/v/release/HKUDS/DeepTutor?style=flat-square&color=brightgreen)](https://github.com/HKUDS/DeepTutor/releases)
[![arXiv](https://img.shields.io/badge/arXiv-2604.26962-b31b1b?style=flat-square&logo=arxiv&logoColor=white)](https://arxiv.org/abs/2604.26962)
[![Discord](https://img.shields.io/badge/Discord-Community-5865F2?style=flat-square&logo=discord&logoColor=white)](https://discord.gg/eRsjPgMU4t)
[![Feishu](https://img.shields.io/badge/Feishu-Group-00D4AA?style=flat-square&logo=feishu&logoColor=white)](./Communication.md)
[![WeChat](https://img.shields.io/badge/WeChat-Group-07C160?style=flat-square&logo=wechat&logoColor=white)](https://github.com/HKUDS/DeepTutor/issues/78)
[Fonctionnalités](#-fonctionnalités-clés) · [Démarrage](#-démarrage) · [Explorer](#-explorer-deeptutor) · [CLI](#%EF%B8%8F-deeptutor-cli--interface-native-à-lagent) · [Écosystème](#-écosystème--eduhub--la-communauté-de-compétences) · [Communauté](#-communauté)
</div>
---
> 🤝 **Nous accueillons toutes les formes de contribution !** Votez sur les éléments de la feuille de route ou proposez-en de nouveaux sur [`Roadmap`](https://github.com/HKUDS/DeepTutor/issues/498), et consultez notre [Guide de contribution](CONTRIBUTING.md) pour la stratégie de branches, les normes de code et comment démarrer.
### 📰 Actualités
- **2026-05-22** 🌐 Site de documentation officiel en ligne sur [**deeptutor.info**](https://deeptutor.info/) — guides, références et tours des capacités en un seul endroit.
- **2026-04-19** 🎉 20 000 étoiles en 111 jours ! Merci pour votre soutien envers un tutorat véritablement personnalisé et intelligent.
- **2026-04-10** 📄 Notre article est en ligne sur arXiv — lisez le [preprint](https://arxiv.org/abs/2604.26962) pour la conception et les idées derrière DeepTutor.
- **2026-02-06** 🚀 10 000 étoiles en seulement 39 jours ! Un immense merci à notre incroyable communauté.
- **2026-01-01** 🎊 Bonne Année ! Rejoignez notre [Discord](https://discord.gg/eRsjPgMU4t), [WeChat](https://github.com/HKUDS/DeepTutor/issues/78), ou les [Discussions](https://github.com/HKUDS/DeepTutor/discussions) — façonnons DeepTutor ensemble.
- **2025-12-29** 🎓 DeepTutor est officiellement lancé !
## ✨ Fonctionnalités Clés
DeepTutor est un espace de travail d'apprentissage natif à l'agent qui connecte le tutorat, la résolution de problèmes, la génération de quiz, la recherche, la visualisation et la pratique de maîtrise dans un système extensible.
- **Un seul runtime pour chaque mode** — Chat, Quiz, Research, Visualize, Solve et Mastery Path fonctionnent sur la même boucle d'agent, vous changez donc l'objectif, pas le moteur, et le contexte suit l'apprenant.
- **Contexte d'apprentissage connecté** — Les bases de connaissances, les livres, les brouillons Co-Writer, les carnets, les banques de questions, les personas et la Memory restent disponibles dans tous les flux de travail au lieu de vivre dans des outils isolés.
- **Sous-agents et Partners** — consultez un Claude Code, Codex ou Partner en direct depuis n'importe quel tour (ou importez leurs conversations passées), et exécutez des compagnons IM persistants sur le même cerveau.
- **Connaissances multi-moteur** — bibliothèques RAG versionnées via LlamaIndex, PageIndex, GraphRAG, LightRAG, ou un vault Obsidian lié, avec une analyse de documents enfichable.
- **Outils et compétences extensibles** — outils intégrés, serveurs MCP, modèles de génération d'images / vidéos / voix, et compétences communautaires installables depuis EduHub.
- **Mémoire inspectable** — les traces L1, les résumés de surface L2 et la synthèse L3 rendent la personnalisation visible et modifiable, avec un Memory Graph qui retrace chaque affirmation jusqu'à son evidence.
---
## 🚀 Démarrage
DeepTutor propose quatre chemins d'installation. Ils partagent tous une même structure d'espace de travail : les paramètres résident dans `data/user/settings/` sous le répertoire depuis lequel vous lancez l'application (ou sous `DEEPTUTOR_HOME` / `deeptutor start --home` si vous en définissez un explicitement). Pour l'application complète, le flux recommandé est **choisir un répertoire d'espace de travail → installer → `deeptutor init` → `deeptutor start`**.
<details>
<summary><b>Option 1 — Installer depuis PyPI</b> · application Web locale complète + CLI, sans clonage</summary>
Application Web locale complète + CLI, sans clonage requis. Nécessite **Python 3.11+** et un runtime **Node.js 20+** dans le PATH (le serveur standalone Next.js packagé est lancé par `deeptutor start`).
```bash
mkdir -p my-deeptutor && cd my-deeptutor
pip install -U deeptutor
deeptutor init # invite pour les ports + fournisseur LLM + embedding optionnel
deeptutor start # démarre le backend + frontend ; gardez le terminal ouvert
```
`deeptutor init` demande le port backend (par défaut `8001`), le port frontend (par défaut `3782`), le fournisseur LLM / URL de base / clé API / modèle, et un fournisseur d'embedding optionnel pour la Base de Connaissances / RAG.
Après `deeptutor start`, ouvrez l'URL frontend affichée dans le terminal — par défaut [http://127.0.0.1:3782](http://127.0.0.1:3782). Appuyez sur `Ctrl+C` dans ce terminal pour arrêter le backend et le frontend. Ignorer `deeptutor init` est possible pour un essai rapide ; l'application démarre avec les ports par défaut et des paramètres de modèle vides, à configurer plus tard dans **Paramètres → Modèles**.
</details>
<details>
<summary><b>Option 2 — Installer depuis les sources</b> · développer à partir d'un checkout</summary>
Pour le développement à partir d'un checkout. Utilisez **Python 3.11+** et **Node.js 22 LTS** pour correspondre à la CI et à Docker.
```bash
git clone https://github.com/HKUDS/DeepTutor.git
cd DeepTutor
# Créer un venv (macOS/Linux). Windows PowerShell :
# py -3.11 -m venv .venv ; .\.venv\Scripts\Activate.ps1
python3 -m venv .venv && source .venv/bin/activate
python -m pip install --upgrade pip
# Installer les dépendances backend + frontend
python -m pip install -e .
( cd web && npm ci --legacy-peer-deps )
deeptutor init
deeptutor start
```
Les installations depuis les sources exécutent Next.js en mode dev contre le répertoire `web/` local ; tout le reste (structure de configuration, ports, arrêt avec `Ctrl+C`) correspond à l'Option 1.
<details>
<summary><b>Environnement Conda</b> (à la place de <code>venv</code>)</summary>
```bash
conda create -n deeptutor python=3.11
conda activate deeptutor
python -m pip install --upgrade pip
```
</details>
<details>
<summary><b>Extras d'installation optionnels</b> — dev / partners / matrix / math-animator</summary>
```bash
pip install -e ".[dev]" # outils de tests/lint
pip install -e ".[partners]" # SDKs de canaux IM Partner + client MCP
pip install -e ".[matrix]" # canal Matrix sans E2EE/libolm
pip install -e ".[matrix-e2e]" # Matrix E2EE ; nécessite libolm
pip install -e ".[math-animator]" # addon Manim ; nécessite LaTeX/ffmpeg/libs système
```
</details>
<details>
<summary><b>Ajustements des dépendances frontend et dépannage du serveur de développement</b></summary>
**Modifier les dépendances frontend :** exécutez `npm install --legacy-peer-deps` pour actualiser `web/package-lock.json`, puis commitez `web/package.json` et `web/package-lock.json`.
**Serveur de développement bloqué :** si `deeptutor start` signale un frontend existant qui ne répond pas, arrêtez le PID qu'il affiche. Si aucun processus Next.js ne tourne réellement, les fichiers de verrou sont périmés — supprimez-les et réessayez :
```bash
rm -f web/.next/dev/lock web/.next/lock
deeptutor start
```
</details>
</details>
<details>
<summary><b>Option 3 — Docker</b> · un conteneur autonome</summary>
Un conteneur pour l'application Web complète. Images sur GitHub Container Registry :
- `ghcr.io/hkuds/deeptutor:latest` — version stable
- `ghcr.io/hkuds/deeptutor:pre` — pré-version, si disponible
> Voir [CONTAINERIZATION.md](./CONTAINERIZATION.md) pour les déploiements podman/rootless/système de fichiers racine en lecture seule et le guide complet par installation.
```bash
docker run --rm --name deeptutor \
-p 127.0.0.1:3782:3782 \
-v deeptutor-data:/app/data \
ghcr.io/hkuds/deeptutor:latest
```
> **Seul le port `3782` doit être publié.** Le navigateur parle exclusivement à l'origine frontend ; le middleware Next.js (`web/proxy.ts`) transmet `/api/*` et `/ws/*` au backend FastAPI **à l'intérieur du conteneur**. La publication de `8001` (`-p 127.0.0.1:8001:8001`) est optionnelle — utile uniquement pour accéder directement à l'API avec curl ou des scripts.
Ouvrez [http://127.0.0.1:3782](http://127.0.0.1:3782). Le conteneur crée `/app/data/user/settings/*.json` au premier démarrage ; configurez les fournisseurs de modèles depuis la page Paramètres Web. La configuration, les clés API, les journaux, les fichiers d'espace de travail, la mémoire et les bases de connaissances persistent dans le volume `deeptutor-data`.
- **Ports hôte différents :** modifiez le côté gauche de chaque correspondance `-p hôte:conteneur` (ex. `-p 127.0.0.1:8088:3782`). Si vous changez les ports côté conteneur dans `/app/data/user/settings/system.json`, redémarrez et mettez à jour le côté droit de chaque correspondance en conséquence.
- **Détaché :** ajoutez `-d`, puis `docker logs -f deeptutor` pour suivre, `docker stop deeptutor` pour arrêter, `docker rm deeptutor` avant de réutiliser le nom. Le volume `deeptutor-data` conserve vos paramètres et votre espace de travail à travers les redémarrages.
**Docker distant / proxy inverse :** le navigateur ne parle qu'à l'origine frontend
(`:3782`) ; le middleware Next.js dans le conteneur transmet `/api/*` et
`/ws/*` au serveur backend côté serveur. Pour le cas courant d'un conteneur unique, vous
ne configurez pas du tout de base API — pointez simplement votre proxy inverse / terminateur TLS
sur `:3782`. Vous n'avez besoin d'une base API que pour un **déploiement séparé**
(backend dans un conteneur/hôte séparé) : définissez `next_public_api_base` dans
`data/user/settings/system.json` avec l'adresse réseau interne que le serveur frontend
utilise pour atteindre le backend (elle est lue côté serveur, jamais envoyée au navigateur).
```json
{
"next_public_api_base": "http://backend:8001"
}
```
`next_public_api_base_external` (et son alias `public_api_base`) sont acceptés comme
solutions de repli à priorité inférieure. CORS utilise les **origines** frontend, pas les URLs d'API. Avec
l'authentification désactivée, DeepTutor autorise les origines de navigateur HTTP/HTTPS normales par défaut.
Avec l'authentification activée, ajoutez les origines frontend exactes :
```json
{
"cors_origins": ["https://deeptutor.example.com"]
}
```
<details>
<summary><b>Connexion à Ollama / LM Studio / llama.cpp / vLLM / Lemonade sur l'hôte</b></summary>
Dans Docker, `localhost` est le conteneur lui-même, pas votre machine hôte. Pour atteindre un service de modèle tournant sur l'hôte, utilisez la passerelle hôte (recommandé) :
```bash
docker run --rm --name deeptutor \
-p 127.0.0.1:3782:3782 -p 127.0.0.1:8001:8001 \
--add-host=host.docker.internal:host-gateway \
-v deeptutor-data:/app/data \
ghcr.io/hkuds/deeptutor:latest
```
Puis dans **Paramètres → Modèles**, pointez l'URL de base du fournisseur vers `host.docker.internal` :
- Ollama LLM : `http://host.docker.internal:11434/v1`
- Ollama embedding : `http://host.docker.internal:11434/api/embed`
- LM Studio : `http://host.docker.internal:1234/v1`
- llama.cpp : `http://host.docker.internal:8080/v1`
- Lemonade : `http://host.docker.internal:13305/api/v1`
Docker Desktop (macOS/Windows) résout généralement `host.docker.internal` sans `--add-host`. Sur Linux, le drapeau est la façon portable de créer ce nom d'hôte avec les versions modernes de Docker Engine.
**Alternative Linux — réseau hôte :** ajoutez `--network=host` et supprimez les drapeaux `-p`. Le conteneur partage directement le réseau hôte, ouvrez donc [http://127.0.0.1:3782](http://127.0.0.1:3782) (ou le `frontend_port` dans `system.json`), et les services hôtes sont accessibles avec des URLs localhost normales comme `http://127.0.0.1:11434/v1`. Notez que le réseau hôte expose les ports du conteneur directement sur l'hôte et peut entrer en conflit avec des services existants — pour les maintenir sur loopback, définissez `BACKEND_HOST=127.0.0.1` et `FRONTEND_HOST=127.0.0.1` (voir [CONTAINERIZATION.md](./CONTAINERIZATION.md)).
</details>
</details>
<details>
<summary><b>Option 4 — CLI uniquement</b> · sans interface Web, depuis un checkout des sources</summary>
Quand vous n'avez pas besoin de l'interface Web. Le paquet CLI uniquement est installé depuis un checkout des sources, pas depuis PyPI.
```bash
git clone https://github.com/HKUDS/DeepTutor.git
cd DeepTutor
# Créer un venv (macOS/Linux). Windows PowerShell :
# py -3.11 -m venv .venv-cli ; .\.venv-cli\Scripts\Activate.ps1
python3 -m venv .venv-cli && source .venv-cli/bin/activate
python -m pip install --upgrade pip
python -m pip install -e ./packaging/deeptutor-cli
deeptutor init --cli
deeptutor chat
```
`deeptutor init --cli` partage la même structure `data/user/settings/` que l'application complète mais ignore les invites de ports backend/frontend et désactive les embeddings par défaut (choisissez `Yes` si vous prévoyez d'utiliser `deeptutor kb …` ou les outils RAG). Il écrit quand même une structure d'exécution complète (`system.json`, `auth.json`, `integrations.json`, `model_catalog.json`, `main.yaml`, `agents.yaml`) et demande quand même le fournisseur LLM actif et le modèle.
<details>
<summary><b>Commandes courantes</b></summary>
```bash
deeptutor chat # REPL interactif
deeptutor chat --capability deep_solve --tool rag --kb my-kb
deeptutor run chat "Explain Fourier transform"
deeptutor run deep_solve "Solve x^2 = 4" --tool rag --kb my-kb
deeptutor kb create my-kb --doc textbook.pdf
deeptutor memory show
deeptutor config show
```
</details>
L'installation locale `deeptutor-cli` n'inclut pas de ressources Web ni de dépendances serveur. Conservez le checkout des sources — l'installation modifiable y pointe. Pour ajouter l'application Web plus tard, installez le paquet PyPI (Option 1) et exécutez `deeptutor init` + `deeptutor start` depuis le même espace de travail.
</details>
<details>
<summary><b>Sandbox d'exécution de code (compétences office)</b> · exécution du code généré par le modèle pour docx / pdf / pptx / xlsx</summary>
Les compétences office intégrées — **docx / pdf / pptx / xlsx** — fonctionnent en demandant au
modèle d'écrire un court script Python (`python-docx`, `reportlab`, `openpyxl`, …),
de l'exécuter via les outils `exec` / `code_execution`, et de renvoyer une URL de téléchargement.
Ces outils se montent chaque fois qu'un backend sandbox est actif, ce qui est le cas **par défaut**
dans chaque forme de déploiement :
- **Local (Option 1 / 2) et Docker (Option 3, conteneur unique) :** un sandbox de sous-processus
restreint exécute le code du modèle (sur l'hôte localement, ou à l'intérieur du
conteneur sous Docker — le conteneur étant sa propre frontière d'isolation).
- **docker-compose :** acheminé à la place vers un **sidecar runner** durci et
à moindres privilèges (`Dockerfile.runner`) via `DEEPTUTOR_SANDBOX_RUNNER_URL`
la posture la plus solide, préférée automatiquement quand elle est présente.
Le sandbox de sous-processus est contrôlé par le paramètre `sandbox_allow_subprocess` dans
`data/user/settings/system.json` (par défaut `true`). Exécuter le code généré par le modèle
sur votre hôte est une vraie décision de confiance — définissez-le à `false` (ou exportez
`DEEPTUTOR_SANDBOX_ALLOW_SUBPROCESS=0`) pour désactiver l'exécution côté hôte, au
coût de ne plus pouvoir produire des fichiers avec les compétences office.
</details>
<details>
<summary><b>Référence de configuration</b> — fichiers de configuration sous <code>data/user/settings/</code> (JSON/YAML)</summary>
Tout ce qui se trouve sous `data/user/settings/` est du JSON/YAML brut. La page **Paramètres** dans le navigateur est l'éditeur recommandé.
| Fichier | Objectif |
|:---|:---|
| `model_catalog.json` | Profils de fournisseurs LLM, embedding et recherche ; clés API ; modèles actifs |
| `system.json` | Ports backend/frontend, base d'API publique, CORS, vérification SSL, répertoire des pièces jointes |
| `auth.json` | Basculement d'authentification optionnel, nom d'utilisateur, hachage de mot de passe, paramètres de jeton/cookie |
| `integrations.json` | Paramètres d'intégration PocketBase et sidecar optionnels |
| `interface.json` | Langue de l'interface / thème / préférences de barre latérale |
| `main.yaml` | Valeurs par défaut du comportement d'exécution et injection de chemin |
| `agents.yaml` | Paramètres de température et de jetons pour les capacités/outils |
Le fichier `.env` à la racine du projet n'est **pas** lu comme fichier de configuration d'application. Pour une configuration minimale de modèle, ouvrez **Paramètres → Modèles**, ajoutez un profil LLM (URL de base / clé API / nom du modèle) et enregistrez. Ajoutez un profil d'embedding uniquement si vous prévoyez d'utiliser les fonctionnalités Base de Connaissances / RAG.
</details>
## 📖 Explorer DeepTutor
Commencez par les surfaces principales que vous utiliserez au quotidien : Chat, Partners, My Agents, Co-Writer, Book, Knowledge Center, Learning Space, Memory et Settings. La visite couvre ensuite les déploiements Multi-Utilisateur pour des espaces de travail partagés et isolés.
<div align="center">
<img src="../../assets/figs/web-1.4.6+/OVERVIEW.png" alt="Accueil DeepTutor — l'espace de travail Chat avec chaque surface dans la barre latérale" width="900">
</div>
<details>
<summary><b>🏗️ Architecture du système</b></summary>
<div align="center">
<img src="../../assets/figs/system/system%20architecture.png" alt="Architecture du système DeepTutor" width="900">
</div>
</details>
<details>
<summary><b>💬 Chat — La Boucle d'Agent que Vous Utilisez Vraiment</b></summary>
Chat est la capacité par défaut et là où commence la plupart du travail. Un seul fil peut discuter normalement, appeler des outils, s'ancrer dans des bases de connaissances sélectionnées, lire des pièces jointes, générer des images, consulter des sous-agents, écrire des enregistrements dans le carnet et continuer avec le même contexte à travers les tours.
<div align="center">
<img src="../../assets/figs/web-1.4.6+/home/00-overview.png" alt="Espace de travail Chat de DeepTutor" width="900">
</div>
La boucle est délibérément simple : le modèle réfléchit en rounds, appelle des outils quand c'est utile, observe les résultats et termine avec un message sans outil. `ask_user` est spécial — plutôt que de deviner, l'agent peut mettre le tour en pause, poser une question de clarification structurée, et reprendre une fois que vous répondez.
<div align="center">
<img src="../../assets/figs/system/chat-agent-loop.png" alt="Boucle d'agent Chat de DeepTutor" width="900">
</div>
Les outils basculables par l'utilisateur sont `brainstorm`, `web_search`, `paper_search`, `reason` et `geogebra_analysis` — plus `imagegen` et `videogen` une fois que vous avez configuré le modèle de génération correspondant. Les outils contextuels tels que `rag`, `read_source`, `read_memory`, `write_memory`, `read_skill`, `load_tools`, `exec`, `web_fetch`, `ask_user`, `list_notebook`, `write_note`, `github` et `consult_subagent` se montent automatiquement quand le tour dispose du bon contexte.
Le contexte se présente en deux types : le **contexte de session persistant** (sous-agent, bases de connaissances, persona, modèle, voix) vit sur la barre d'outils du compositeur et persiste entre les tours ; les **références ponctuelles** (fichiers, historique de chat, livres, carnets, banque de questions, agents importés) proviennent du menu `+` pour un seul tour.
Chat est aussi le point de lancement pour des capacités plus profondes : **Quiz** pour la génération de questions, **Research** pour les rapports cités, **Visualize** pour les graphiques / diagrammes / animations, et — sous *Plus de Capacités***Solve** pour le raisonnement guidé et **Mastery Path** pour les flux de plans d'apprentissage.
</details>
<details>
<summary><b>🤝 Partner — Compagnons Persistants sur le Même Cerveau</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/partners/00-partners%20overview.png" alt="Espace de travail Partners de DeepTutor" width="900">
</div>
Les Partners sont des compagnons persistants avec leur propre âme, politique de modèle, bibliothèque, mémoire et canaux. Ce ne sont pas un moteur de bot séparé : chaque message web ou IM entrant devient un tour normal de `ChatOrchestrator` dans un espace de travail à portée partner. Un partner est « un chat qui a une personnalité et un numéro de téléphone. »
<div align="center">
<img src="../../assets/figs/system/partners-architecture.png" alt="Architecture Partners de DeepTutor" width="900">
</div>
Chaque partner a un `SOUL.md`, une sélection de modèle, des canaux, une politique d'outils et une bibliothèque assignée. Les bases de connaissances, les compétences et les carnets sont copiés dans `data/partners/<id>/workspace/`, de sorte que les mêmes outils RAG, compétence, carnet et mémoire fonctionnent sans cas particuliers. Un partner lit la mémoire de son propriétaire mais n'écrit que la sienne.
<div align="center">
<img src="../../assets/figs/web-1.4.6+/partners/02-IM%20config%20for%20each%20partner.png" alt="Configuration du canal IM par partner" width="900">
</div>
La couche de canaux est pilotée par schéma et peut se connecter à des plateformes IM telles que Feishu, Telegram, Slack, Discord, DingTalk, QQ/NapCat, WeCom, WhatsApp, Zulip, Mattermost, Matrix, Mochat et Microsoft Teams selon les extras installés et les identifiants configurés. Un partner peut également être connecté comme sous-agent et consulté depuis un tour de chat normal — voir **My Agents** ci-dessous.
</details>
<details>
<summary><b>🧑‍🚀 My Agents — Consulter et Importer d'Autres Agents</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/myagents/00-overview.png" alt="Espace de travail My Agents de DeepTutor" width="900">
</div>
My Agents transforme d'autres agents en contexte pour DeepTutor, et fait deux choses distinctes. **Connectez un agent en direct** — un Claude Code ou Codex CLI sur votre machine, ou l'un de vos Partners — et consultez-le depuis l'intérieur d'un tour de chat : DeepTutor *exécute* réellement l'autre agent et diffuse son travail dans le panneau d'Activité via l'outil `consult_subagent`. Sélectionnez-le avec la puce Agent (ou tapez `@`), et définissez combien de rounds la consultation peut prendre.
<div align="center">
<img src="../../assets/figs/web-1.4.6+/home/08-subagent%20demo%20with%20claude%20code.png" alt="Consultation d'un sous-agent Claude Code en direct" width="900">
</div>
**Importez des conversations passées** — apportez votre historique Claude Code et Codex existant comme des agents nommés, consultables et reprenables. Choisissez les jours à importer ; l'actualisation les re-synchronise. Référencez une conversation importée depuis n'importe quel tour de chat via `+` → My Agents, et DeepTutor la lit comme une transcription tierce — elle reste *leur* conversation, pas la voix propre de DeepTutor.
</details>
<details>
<summary><b>✍️ Co-Writer — Rédaction Markdown Sensible à la Sélection</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/co-writer/00-overview.png" alt="Espace de travail Co-Writer de DeepTutor" width="900">
</div>
Co-Writer est un espace de travail Markdown à vue divisée pour les rapports, tutoriels, notes et artefacts d'apprentissage longs. Les documents se sauvegardent automatiquement et affichent un aperçu en direct (math KaTeX, clôtures de diagrammes), et peuvent être enregistrés dans des carnets quand un brouillon devient un contexte réutilisable.
<div align="center">
<img src="../../assets/figs/web-1.4.6+/co-writer/01-edit%20panel.png" alt="Éditeur Co-Writer avec aperçu en direct" width="900">
</div>
Son idée directrice est l'**édition chirurgicale** : sélectionnez une plage et demandez à DeepTutor de la réécrire, l'étendre ou la raccourcir. L'agent d'édition peut ancrer le changement dans une base de connaissances ou des preuves web, conserve une trace de ses appels d'outils, et montre chaque changement comme un diff accepter/rejeter — rien ne se place donc jusqu'à ce que vous l'approuviez.
</details>
<details>
<summary><b>📖 Book — Livres Vivants depuis Vos Matériaux</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/book/00-book_overview.png" alt="Bibliothèque de livres DeepTutor" width="900">
</div>
Book transforme des sources sélectionnées en un **livre vivant** interactif — pas un PDF statique, mais un environnement de lecture construit à partir de blocs typés. Un livre peut démarrer depuis des bases de connaissances, des carnets, des banques de questions ou l'historique de chat ; le flux de création propose un plan de chapitre avant que le contenu soit généré, vous pouvez donc revoir la forme au lieu d'accepter une sortie en un seul coup aveugle.
<p align="center">
<img src="../../assets/figs/web-1.4.6+/book/01-book-demo-quiz%20card.png" alt="Bloc quiz du livre" width="31%">
&nbsp;
<img src="../../assets/figs/web-1.4.6+/book/02-book-demo-manim%20video.png" alt="Bloc animation Manim du livre" width="31%">
&nbsp;
<img src="../../assets/figs/web-1.4.6+/book/03-book-demo%20interactive%20module.png" alt="Bloc widget interactif du livre" width="31%">
</p>
Chaque chapitre se compile en blocs typés — texte, encadrés, quiz, fiches, chronologies, code, figures, HTML interactif, animations, graphes de concepts, approfondissements et notes utilisateur — et chaque page a son propre Chat de Page. Les blocs sont modifiables : insérez, déplacez, régénérez ou changez le type d'un bloc sans réécrire le chapitre. Les commandes de maintenance comme `deeptutor book health` et `deeptutor book refresh-fingerprints` aident à détecter quand les connaissances source ont divergé des pages compilées.
</details>
<details>
<summary><b>📚 Knowledge Center — Bibliothèques RAG Multi-Moteur</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/knowledge/00-overview.png" alt="Knowledge Center de DeepTutor" width="900">
</div>
Les bases de connaissances sont les collections de documents derrière le RAG — elles ancrent les tours de Chat, les éditions Co-Writer, la génération de Book et les conversations Partner. Ce qui est distinctif est un **choix de moteurs de récupération** : **LlamaIndex** (par défaut, vecteur local + BM25), **PageIndex** (hébergé, récupération par raisonnement avec citations au niveau de la page), **GraphRAG** et **LightRAG** (récupération par graphe de connaissances), **LightRAG Server** (récupération déléguée à une instance LightRAG externe connectée via HTTP), ou un vault **Obsidian** lié que le tuteur lit et écrit en place. Chaque KB est liée à un moteur.
<div align="center">
<img src="../../assets/figs/web-1.4.6+/knowledge/01-create%20knowledge%20base.png" alt="Créer une base de connaissances" width="900">
</div>
En créant une KB, vous choisissez soit de **créer nouvelle** (uploadez des documents et construisez un index frais) soit de **lier une existante** (réutilisez un index construit ailleurs, lu en place sans re-indexation). La re-indexation écrit un nouveau répertoire plat `version-N` et conserve les précédents, donc un index fonctionnel n'est jamais détruit en milieu de reconstruction. Un seul document peut être supprimé même d'une base en état d'**erreur** — retirer un fichier dont l'analyse a échoué sans devoir tout supprimer et reconstruire. L'analyse de documents — Text-only, MinerU, Docling, markitdown ou PyMuPDF4LLM — est choisie dans **Paramètres → Base de Connaissances**, avec les téléchargements de modèles locaux désactivés par défaut. La CLI reprend le cycle de vie avec `deeptutor kb list`, `info`, `create`, `add`, `search`, `set-default` et `delete`.
</details>
<details>
<summary><b>🌐 Learning Space — Compétences, Personas et Contexte Réutilisable</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/learning-space/00-overview.png" alt="Hub Learning Space de DeepTutor" width="900">
</div>
Learning Space est la couche de bibliothèque et de personnalisation — là où vivent les choses qui persistent. **Conversations & Matériaux** contient votre historique de chat, vos carnets et une banque de questions (chaque question sauvegardée conserve votre réponse, la réponse de référence et une explication). **Personnalisation** contient les parcours de maîtrise, les personas (préréglages de comportement comme *pair*, *assistant de recherche*, *enseignant*) et les compétences (livrets de jeu `SKILL.md` que le modèle lit à la demande). Tout ici peut être réutilisé depuis Chat, Partners, Co-Writer et Book.
<div align="center">
<img src="../../assets/figs/web-1.4.6+/learning-space/07-%20download%20skills%20from%20eduhub.png" alt="Importer des compétences depuis EduHub" width="900">
</div>
Vous n'avez pas à écrire chaque compétence vous-même — **Importer depuis EduHub** parcourt le catalogue communautaire et télécharge une compétence directement dans votre bibliothèque via une porte de sécurité (voir [Écosystème](#-écosystème--eduhub--la-communauté-de-compétences)).
</details>
<details>
<summary><b>🧠 Memory — Personnalisation Inspectable</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/memory/00-overview.png" alt="Aperçu de la mémoire DeepTutor" width="900">
</div>
Memory est un système en trois couches sauvegardé sur fichier que vous pouvez lire, organiser et auditer — délibérément *pas* un store vectoriel caché. **L1** est le miroir de l'espace de travail plus une trace d'événements en ajout seul (`trace/<surface>/<date>.jsonl`) ; **L2** contient des faits organisés par surface (`L2/<surface>.md`) ; **L3** est la synthèse inter-surfaces (`L3/<profile|recent|scope|preferences>.md`). Parce que L2 cite L1 et L3 cite L2, rien dans votre profil n'est sans compte rendu.
<div align="center">
<img src="../../assets/figs/web-1.4.6+/memory/01-3%20layer%20memory%20graph.png" alt="Graphe de mémoire DeepTutor" width="900">
</div>
Le Memory Graph montre toute la pyramide — la synthèse L3 au centre, L2 dans l'anneau du milieu, les traces L1 à l'extérieur — vous pouvez donc retracer n'importe quelle affirmation synthétisée jusqu'à l'événement brut exact qui la sous-tend. La Memory est suivie sur les surfaces `chat`, `notebook`, `quiz`, `kb`, `book`, partner et `cowriter` ; les budgets Mise à jour / Audit / Déduplication du consolidateur sont réglés dans **Paramètres → Memory**.
</details>
<details>
<summary><b>⚙️ Settings — Un Seul Plan de Contrôle</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/settings/00-setting%20overview.png" alt="Hub Settings de DeepTutor" width="900">
</div>
Settings est le plan de contrôle opérationnel, avec une bande de statut en direct (Backend, LLM, Embedding, Recherche) et une carte par zone : **Apparence** (thème + langue de l'interface), **Réseau** (base d'API, ports, CORS), **Modèles** (LLM, Embedding, Recherche, Texte-à-Parole, Parole-à-Texte, Génération d'Images, Génération de Vidéos), **Base de Connaissances** (moteur d'analyse de documents), **Chat** (outils, serveurs MCP, paramètres par capacité), **Partners & Agents** (les sous-agents que vous pouvez consulter depuis un tour), et **Memory** (les budgets du consolidateur).
<div align="center">
<img src="../../assets/figs/web-1.4.6+/settings/01-appearance%20settings.png" alt="Paramètres d'apparence et thèmes DeepTutor" width="900">
</div>
La plupart des sections utilisent un flux brouillon-et-application, vous pouvez donc tester un fournisseur avant de vous y engager. Quatre thèmes sont livrés dans la boîte — Default, Cream, Dark et Glass. Les fichiers `.env` à la racine du projet sont intentionnellement ignorés ; la configuration d'exécution vit sous `data/user/settings/*.json` sauf si `DEEPTUTOR_HOME` ou `deeptutor start --home` pointe l'application ailleurs.
</details>
<details>
<summary><b>👥 Multi-Utilisateur — Déploiements Partagés</b> · authentification optionnelle, espaces de travail isolés par utilisateur</summary>
L'authentification est **désactivée par défaut** — DeepTutor fonctionne en mode mono-utilisateur. Activez-la et un seul arbre `data/` héberge un espace de travail admin, des espaces de travail per-utilisateur isolés et des espaces de travail partner côte à côte :
```text
data/
├── user/ # Espace de travail Admin + paramètres globaux
├── users/<uid>/ # Portée par utilisateur : historique de chat, mémoire, carnets, KB
├── partners/<id>/workspace/ # Portée partner (utilisateur synthétique)
└── system/ # auth/users.json · grants/<uid>.json · audit/usage.jsonl
```
Le **premier utilisateur enregistré devient admin** et possède les catalogues de modèles, les identifiants de fournisseur, les bases de connaissances partagées, les compétences et les attributions per-utilisateur. Tous les autres obtiennent un espace de travail isolé et une page Settings expurgée — les modèles, KB et compétences assignés par l'admin apparaissent comme des options à portée, en lecture seule, jamais comme des clés d'API brutes.
**Activer :** activez l'auth dans `data/user/settings/auth.json`, redémarrez `deeptutor start`, enregistrez le premier admin sur `/register`, puis ajoutez des utilisateurs depuis `/admin/users` et assignez des modèles, KB, compétences, Partners, politique d'outils/MCP et accès à l'exécution de code via des attributions.
> PocketBase reste une intégration mono-utilisateur — gardez `integrations.pocketbase_url` vide pour les déploiements multi-utilisateur sauf si vous avez configuré un store utilisateur externe.
</details>
## ⌨️ DeepTutor CLI — Interface Native à l'Agent
Un seul binaire `deeptutor`, deux façons d'accéder : un **REPL** interactif pour ceux qui vivent dans le terminal, et du **JSON** structuré pour d'autres agents qui pilotent DeepTutor comme un outil. Les mêmes capacités, outils et bases de connaissances dans les deux cas.
<details>
<summary><b>Piloter vous-même</b></summary>
`deeptutor chat` ouvre un REPL interactif ; `deeptutor run <capacité> "<message>"` exécute un seul tour et quitte. Les deux acceptent les mêmes drapeaux `--capability`, `--tool`, `--kb` et `--config`.
```bash
deeptutor chat # REPL interactif
deeptutor chat --capability deep_solve --kb my-kb --tool rag
deeptutor run chat "Explain the Fourier transform" --tool rag --kb textbook
deeptutor run deep_research "Survey 2026 papers on RAG" \
--config mode=report --config depth=standard
```
Tout ce que fait l'application Web est également disponible ici — bases de connaissances (`kb`), sessions (`session`), partners (`partner`), compétences (`skill`), carnets, mémoire et configuration. Liste complète ci-dessous.
</details>
<details>
<summary><b>Laisser un agent piloter</b></summary>
DeepTutor est conçu pour être *opéré par un autre agent*. Ajoutez `--format json` à n'importe quel `run` et chaque tour diffuse du **NDJSON — un événement par ligne** (`content`, `tool_call`, `tool_result`, `done`, …), chaque ligne étant taguée avec son `session_id`. Les exécutions sont headless-safe : une pause `ask_user` sans TTY se résout automatiquement avec une réponse vide au lieu de bloquer.
```bash
# Coup unique, lisible par machine
deeptutor run deep_solve "Find d/dx[sin(x^2)]" --tool reason --format json
# Enchaîner des tours dans une session avec état — capturer l'id, le réutiliser
SID=$(deeptutor run deep_research "Survey 2026 papers on RAG" \
--config mode=report --config depth=standard --format json \
| jq -r 'select(.type=="done").session_id')
deeptutor run deep_question "Quiz me on that survey" --session "$SID" --format json
```
Le dépôt inclut un [`SKILL.md`](SKILL.md) racine — un document de passation de ~150 lignes qui enseigne à tout LLM utilisant des outils la totalité de la surface en une seule lecture. Remettez-le à Claude Code, Codex ou OpenCode (ils récupèrent `SKILL.md` automatiquement), ou enveloppez `deeptutor run` comme un outil dans une boucle LangChain / AutoGen. Recettes complètes : [Agent Handoff](https://deeptutor.info/docs/cli/agent-handoff/).
</details>
<details>
<summary><b>Référence des commandes</b></summary>
| Commande | Description |
|:---|:---|
| `deeptutor init` | Créer ou mettre à jour `data/user/settings` pour l'espace de travail actuel |
| `deeptutor start [--home PATH]` | Lancer le backend + frontend ensemble |
| `deeptutor serve [--port PORT]` | Démarrer uniquement le backend FastAPI |
| `deeptutor run <capacité> <message>` | Exécuter un seul tour de capacité (`chat`, `deep_solve`, `deep_question`, `deep_research`, `visualize`, `math_animator`, `mastery_path`) ; ajoutez `--format json` pour la sortie NDJSON |
| `deeptutor chat` | REPL interactif avec contrôles de capacité, outil, KB, carnet et historique |
| `deeptutor partner list/create/start/stop` | Gérer les partners connectés à IM |
| `deeptutor kb list/info/create/add/search/set-default/delete` | Gérer les bases de connaissances LlamaIndex |
| `deeptutor skill search/install/list/remove/login/logout/publish/update` | Gérer les compétences, installer depuis les hubs et publier les siennes (`eduhub:<slug>` par défaut, voir Écosystème) |
| `deeptutor memory show/clear` | Inspecter les documents de mémoire L2/L3 ou effacer la mémoire L1/toute |
| `deeptutor session list/show/open/rename/delete` | Gérer les sessions partagées |
| `deeptutor notebook list/create/show/add-md/replace-md/remove-record` | Gérer les carnets depuis des fichiers Markdown |
| `deeptutor book list/health/refresh-fingerprints` | Inspecter les livres et actualiser les empreintes des sources |
| `deeptutor plugin list/info` | Inspecter les outils et capacités enregistrés |
| `deeptutor config show` | Afficher le résumé de configuration |
| `deeptutor provider login <fournisseur>` | Auth du fournisseur (OAuth login `openai-codex` ; `github-copilot` valide une session auth Copilot existante) |
</details>
<details>
<summary><b>Distribution CLI uniquement</b></summary>
Le paquet CLI uniquement se trouve dans `packaging/deeptutor-cli`. Dans ce checkout, installez-le depuis les sources :
```bash
python -m pip install -e ./packaging/deeptutor-cli
```
Il n'est pas encore publié sur PyPI, donc la section principale [Démarrage](#-démarrage) conserve le chemin d'installation depuis les sources.
</details>
## 🧩 Écosystème — EduHub & la Communauté de Compétences
Les compétences DeepTutor utilisent le format ouvert **Agent-Skills** — un dossier avec un livret de jeu `SKILL.md` (frontmatter YAML + Markdown) et des fichiers de référence optionnels. Rien dans ce format n'est spécifique à DeepTutor, donc tout registre qui parle le format devient une source pour votre bibliothèque. DeepTutor inclut **[EduHub](https://eduhub.deeptutor.info/)** — notre propre registre de compétences axé sur l'éducation — configuré comme hub par défaut.
<details>
<summary><b>EduHub — l'écosystème de compétences de DeepTutor</b></summary>
[**EduHub**](https://eduhub.deeptutor.info/) est le hub communautaire que DeepTutor a lancé pour partager des compétences d'agent orientées enseignement — tuteurs socratiques, constructeurs de fiches, retours sur les essais, plans d'examen, explicateurs de concepts, et plus encore. Il est intégré à DeepTutor, il n'y a donc rien à configurer : un slug nu ou un préfixe `eduhub:` le résout.
**Trouver et installer** — dans le navigateur, ouvrez **Learning Space → Compétences → Importer depuis EduHub** pour parcourir le catalogue et télécharger une compétence directement dans votre bibliothèque. Depuis le terminal :
```bash
deeptutor skill search "socratic tutor" # rechercher sur EduHub (le hub par défaut)
deeptutor skill install socratic-tutor # récupérer → vérifier → enregistrer
deeptutor skill install eduhub:socratic-tutor@1.2.0 # épingler un hub et une version
deeptutor skill list # compétences locales avec leur provenance de hub
```
**Publiez la vôtre** — emballez un `SKILL.md` et partagez-le avec la communauté :
```bash
deeptutor skill login # connexion navigateur à EduHub
deeptutor skill publish ./my-skill # interactif : choisir une piste + étiquettes, puis uploader
deeptutor skill update # revenir en arrière ou publier une nouvelle version
```
EduHub est également un registre autonome compatible ClawHub, de sorte que les agents qui ne sont pas DeepTutor (Claude Code, Codex, …) peuvent l'utiliser directement via le CLI `eduhub``npx eduhub install socratic-tutor`.
</details>
<details>
<summary><b>La porte de sécurité d'importation</b></summary>
Quelle que soit la source, chaque importation passe la **même porte de sécurité** avant que quoi que ce soit ne touche votre espace de travail :
- le **verdict de sécurité** du registre est vérifié en premier — les paquets signalés sont refusés sauf si vous passez `--allow-unverified` ;
- les archives sont extraites défensivement (protections zip-slip / zip-bomb) derrière une **liste blanche de suffixes** texte/script, donc les binaires n'atterrissent jamais dans l'espace de travail ;
- le frontmatter est normalisé selon le schéma de DeepTutor et `always:` est **supprimé**, donc une compétence téléchargée ne peut jamais se forcer dans chaque prompt système ;
- la provenance — hub, version, verdict et heure d'installation — est écrite dans `.hub-lock.json` pour les audits et les mises à jour.
Dans les déploiements multi-utilisateur, l'installation est réservée à l'admin : une nouvelle compétence atterrit dans le catalogue admin et reste invisible aux autres utilisateurs jusqu'à ce qu'une attribution l'assigne, permettant à un admin de la vérifier avant de la déployer.
</details>
<details>
<summary><b>Également compatible avec ClawHub</b></summary>
Parce que DeepTutor parle le format ouvert Agent-Skills, **[ClawHub](https://clawhub.ai/)** fonctionne aussi comme une source de première classe — il est intégré aux côtés d'EduHub. Choisissez-le avec le préfixe hub :
```bash
deeptutor skill search "git release notes" --hub clawhub
deeptutor skill install clawhub:git-release-notes@1.0.1
```
Ajoutez d'autres registres dans `settings/skill_hubs.json` : une entrée `type: "clawhub"` pointe vers n'importe quelle API HTTP compatible (EduHub et ClawHub parlent tous deux ce protocole), `type: "command"` enveloppe n'importe quelle CLI de récupération qu'un registre fournit, et `"default"` choisit le hub utilisé pour les slugs nus. Tous alimentent la même porte d'importation.
</details>
## 🌐 Communauté
### 📮 Contact
DeepTutor est un projet open-source dirigé par [Bingxi Zhao](https://github.com/pancacake) au sein du groupe [HKUDS](https://github.com/HKUDS), et il itère sous une **forme entièrement open-source**, construit ensemble avec la communauté. Jusqu'à présent, nous **N'AVONS PAS** de produits en ligne payants sous quelque forme que ce soit. N'hésitez pas à nous contacter à **bingxizhao39@gmail.com** pour des discussions, des idées ou des collaborations.
### 🙏 Remerciements
Nos plus sincères remerciements à [**Chao Huang**](https://sites.google.com/view/chaoh), directeur du Data Intelligence Lab @ HKU, et à nos collègues du laboratoire HKUDS pour leur soutien chaleureux — en particulier [**Jiahao Zhang**](https://github.com/zzhtx258), [**Zirui Guo**](https://github.com/LarFii) et [**Xubin Ren**](https://github.com/Re-bin). Nous sommes également profondément reconnaissants envers la **communauté open-source** : vos étoiles, issues, pull requests et discussions façonnent DeepTutor chaque jour.
DeepTutor se tient également sur les épaules de remarquables projets open-source qui nous ont fourni à la fois des outils et de l'inspiration :
| Projet | Rôle / Inspiration |
|:---|:---|
| [**LlamaIndex**](https://github.com/run-llama/llama_index) | Pipeline RAG et colonne vertébrale d'indexation de documents |
| [**nanobot**](https://github.com/HKUDS/nanobot) | Moteur d'agent ultra-léger qui a propulsé le TutorBot original *(HKUDS)* |
| [**LightRAG**](https://github.com/HKUDS/LightRAG) | RAG simple & rapide *(HKUDS)* |
| [**AutoAgent**](https://github.com/HKUDS/AutoAgent) | Framework d'agent sans code *(HKUDS)* |
| [**AI-Researcher**](https://github.com/HKUDS/AI-Researcher) | Pipeline de recherche automatisée *(HKUDS)* |
| [**OpenClaw**](https://github.com/openclaw/openclaw) | Passerelle d'agent ouverte et écosystème de compétences derrière ClawHub |
| [**Codex**](https://github.com/openai/codex) | CLI de codage natif à l'agent qui a inspiré notre flux de travail CLI |
| [**Claude Code**](https://github.com/anthropics/claude-code) | CLI de codage agentique qui a inspiré la boucle d'agent DeepTutor |
| [**ManimCat**](https://github.com/Wing900/ManimCat) | Génération d'animations mathématiques pilotée par IA pour Math Animator |
### 🗺️ Feuille de Route & Contribution
Nous voulons que DeepTutor continue d'itérer et de s'améliorer — et finalement de devenir un cadeau que nous offrons en retour à la communauté open-source. Notre [**feuille de route**](https://github.com/HKUDS/DeepTutor/issues/498) est mise à jour en continu ; votez sur les éléments ou proposez-en de nouveaux. Si vous souhaitez contribuer, consultez le [**Guide de contribution**](CONTRIBUTING.md) pour la stratégie de branches, les normes de code et comment démarrer.
<div align="center">
Nous espérons que DeepTutor deviendra un cadeau pour la communauté. 🎁
<a href="https://github.com/HKUDS/DeepTutor/graphs/contributors">
<img src="https://contrib.rocks/image?repo=HKUDS/DeepTutor&max=999" alt="Contributeurs" />
</a>
</div>
<div align="center">
<a href="https://www.star-history.com/#HKUDS/DeepTutor&type=timeline&legend=top-left">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=HKUDS/DeepTutor&type=timeline&theme=dark&legend=top-left" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=HKUDS/DeepTutor&type=timeline&legend=top-left" />
<img alt="Graphique d'historique des étoiles" src="https://api.star-history.com/svg?repos=HKUDS/DeepTutor&type=timeline&legend=top-left" />
</picture>
</a>
</div>
<p align="center">
<a href="https://www.star-history.com/hkuds/deeptutor">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/badge?repo=HKUDS/DeepTutor&theme=dark" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/badge?repo=HKUDS/DeepTutor" />
<img alt="Classement Historique des Étoiles" src="https://api.star-history.com/badge?repo=HKUDS/DeepTutor" />
</picture>
</a>
</p>
<div align="center">
Sous licence [Apache License 2.0](LICENSE).
<p>
<img src="https://visitor-badge.laobi.icu/badge?page_id=HKUDS.DeepTutor&style=for-the-badge&color=00d4ff" alt="Vues">
</p>
</div>
+709
View File
@@ -0,0 +1,709 @@
<div align="center">
<p align="center"><img src="../../assets/figs/logo/logo.png" alt="DeepTutor logo" height="56" style="vertical-align: middle;">&nbsp;<img src="../../assets/figs/logo/banner.png" alt="DeepTutor" height="48" style="vertical-align: middle;"></p>
# DeepTutor: लाइफलॉन्ग व्यक्तिगत ट्यूटरिंग
<p align="center">
<a href="https://deeptutor.info" target="_blank"><img alt="Docs — deeptutor.info" src="https://img.shields.io/badge/Docs-deeptutor.info%20%E2%86%97-0A0A0A?style=for-the-badge&labelColor=F5F5F4" height="36"></a>
</p>
<p align="center">
<a href="https://trendshift.io/repositories/17099?utm_source=repository-badge&amp;utm_medium=badge&amp;utm_campaign=badge-repository-17099" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/repositories/17099" alt="HKUDS%2FDeepTutor | Trendshift" width="250" height="55"/></a>&nbsp;
<a href="https://trendshift.io/repositories/17099?utm_source=trendshift-badge&amp;utm_medium=badge&amp;utm_campaign=badge-trendshift-17099" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/17099/daily" alt="HKUDS%2FDeepTutor | Trendshift" width="250" height="55"/></a>&nbsp;
<a href="https://trendshift.io/repositories/17099?utm_source=trendshift-badge&amp;utm_medium=badge&amp;utm_campaign=badge-trendshift-17099" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/17099/weekly?language=Python" alt="HKUDS%2FDeepTutor | Trendshift" width="250" height="55"/></a>
</p>
<p align="center">
<a href="../../README.md"><img alt="English" height="40" src="https://img.shields.io/badge/English-CDCFD4"></a>&nbsp;
<a href="README_CN.md"><img alt="简体中文" height="40" src="https://img.shields.io/badge/简体中文-CDCFD4"></a>&nbsp;
<a href="README_JA.md"><img alt="日本語" height="40" src="https://img.shields.io/badge/日本語-CDCFD4"></a>&nbsp;
<a href="README_ES.md"><img alt="Español" height="40" src="https://img.shields.io/badge/Español-CDCFD4"></a>&nbsp;
<a href="README_FR.md"><img alt="Français" height="40" src="https://img.shields.io/badge/Français-CDCFD4"></a>&nbsp;
<a href="README_AR.md"><img alt="Arabic" height="40" src="https://img.shields.io/badge/Arabic-CDCFD4"></a>&nbsp;
<a href="README_RU.md"><img alt="Русский" height="40" src="https://img.shields.io/badge/Русский-CDCFD4"></a>&nbsp;
<a href="README_HI.md"><img alt="Hindi" height="40" src="https://img.shields.io/badge/Hindi-BCDCF7"></a>&nbsp;
<a href="README_PT.md"><img alt="Português" height="40" src="https://img.shields.io/badge/Português-CDCFD4"></a>&nbsp;
<a href="README_TH.md"><img alt="Thai" height="40" src="https://img.shields.io/badge/Thai-CDCFD4"></a>&nbsp;
<a href="README_PL.md"><img alt="Polski" height="40" src="https://img.shields.io/badge/Polski-CDCFD4"></a>
</p>
[![Python 3.11+](https://img.shields.io/badge/Python-3.11%2B-3776AB?style=flat-square&logo=python&logoColor=white)](https://www.python.org/downloads/)
[![Next.js 16](https://img.shields.io/badge/Next.js-16-000000?style=flat-square&logo=next.js&logoColor=white)](https://nextjs.org/)
[![License](https://img.shields.io/badge/License-Apache_2.0-blue?style=flat-square)](../../LICENSE)
[![GitHub release](https://img.shields.io/github/v/release/HKUDS/DeepTutor?style=flat-square&color=brightgreen)](https://github.com/HKUDS/DeepTutor/releases)
[![arXiv](https://img.shields.io/badge/arXiv-2604.26962-b31b1b?style=flat-square&logo=arxiv&logoColor=white)](https://arxiv.org/abs/2604.26962)
[![Discord](https://img.shields.io/badge/Discord-Community-5865F2?style=flat-square&logo=discord&logoColor=white)](https://discord.gg/eRsjPgMU4t)
[![Feishu](https://img.shields.io/badge/Feishu-Group-00D4AA?style=flat-square&logo=feishu&logoColor=white)](../../Communication.md)
[![WeChat](https://img.shields.io/badge/WeChat-Group-07C160?style=flat-square&logo=wechat&logoColor=white)](https://github.com/HKUDS/DeepTutor/issues/78)
[विशेषताएं](#-मुख्य-विशेषताएं) · [शुरू करें](#-शुरू-करें) · [एक्सप्लोर करें](#-deeptutor-को-एक्सप्लोर-करें) · [CLI](#-deeptutor-cli--एजेंट-नेटिव-इंटरफेस) · [इकोसिस्टम](#-इकोसिस्टम--eduhub-और-skills-community) · [समुदाय](#-समुदाय)
</div>
---
> 🤝 **हम किसी भी प्रकार के योगदान का स्वागत करते हैं!** [`Roadmap`](https://github.com/HKUDS/DeepTutor/issues/498) पर roadmap items के लिए वोट करें या नए प्रस्तावित करें, और branching strategy, coding standards और शुरू करने के तरीके के लिए हमारी [Contributing Guide](../../CONTRIBUTING.md) देखें।
### 📰 समाचार
- **2026-05-22** 🌐 आधिकारिक डॉक्स साइट [**deeptutor.info**](https://deeptutor.info/) पर live — guides, references, और capability tours एक ही जगह।
- **2026-04-19** 🎉 111 दिनों में 20k स्टार्स! सच्ची व्यक्तिगत, बुद्धिमान ट्यूटरिंग की दिशा में आपके अविश्वसनीय समर्थन के लिए धन्यवाद।
- **2026-04-10** 📄 हमारा paper अब arXiv पर live है — DeepTutor के design और विचारों के लिए [preprint](https://arxiv.org/abs/2604.26962) पढ़ें।
- **2026-02-06** 🚀 39 दिनों में 10k स्टार्स! हमारे अविश्वसनीय community के समर्थन के लिए बहुत धन्यवाद।
- **2026-01-01** 🎊 नया साल मुबारक! हमारे [Discord](https://discord.gg/eRsjPgMU4t), [WeChat](https://github.com/HKUDS/DeepTutor/issues/78), या [Discussions](https://github.com/HKUDS/DeepTutor/discussions) से जुड़ें — आइए मिलकर DeepTutor को आकार दें।
- **2025-12-29** 🎓 DeepTutor आधिकारिक रूप से जारी हुआ!
## ✨ मुख्य विशेषताएं
DeepTutor एक agent-native learning workspace है जो tutoring, problem solving, quiz generation, research, visualization, और mastery practice को एक extensible system में जोड़ता है।
- **हर मोड के लिए एक रनटाइम** — Chat, Quiz, Research, Visualize, Solve और Mastery Path एक ही agent loop पर चलते हैं, इसलिए आप objective बदलते हैं, engine नहीं, और context learner के साथ बना रहता है।
- **जुड़ा हुआ लर्निंग कॉन्टेक्स्ट** — Knowledge bases, books, Co-Writer drafts, notebooks, question banks, personas, और Memory सभी workflows में उपलब्ध रहते हैं, isolated tools में बंद रहने की बजाय।
- **सब-एजेंट और Partners** — किसी भी turn से live Claude Code, Codex, या Partner से सलाह लें (या उनकी पिछली conversations import करें), और same brain पर persistent IM companions चलाएं।
- **मल्टी-इंजन नॉलेज** — LlamaIndex, PageIndex, GraphRAG, LightRAG या linked Obsidian vault के साथ versioned RAG libraries, pluggable document parsing के साथ।
- **एक्सटेंसिबल टूल्स और स्किल्स** — built-in tools, MCP servers, image / video / voice generation models, और EduHub से installable community skills।
- **इंस्पेक्टेबल मेमोरी** — L1 traces, L2 surface summaries, और L3 synthesis personalization को visible और editable बनाते हैं, एक Memory Graph के साथ जो हर दावे को उसके साक्ष्य तक trace करता है।
---
## 🚀 शुरू करें
DeepTutor चार installation paths के साथ आता है। वे सभी एक workspace layout साझा करते हैं: settings उस directory के नीचे `data/user/settings/` में रहती हैं जहां से आप launch करते हैं (या `DEEPTUTOR_HOME` / `deeptutor start --home` के नीचे अगर आप explicitly set करते हैं)। पूरे app के लिए, recommended flow है **workspace directory चुनें → install करें → `deeptutor init` → `deeptutor start`**
<details>
<summary><b>Option 1 — PyPI से Install करें</b> · पूरा local Web app + CLI, clone की जरूरत नहीं</summary>
पूरा local Web app + CLI, clone की जरूरत नहीं। **Python 3.11+** और PATH पर **Node.js 20+** runtime चाहिए (`deeptutor start` packaged Next.js standalone server को spawn करता है)।
```bash
mkdir -p my-deeptutor && cd my-deeptutor
pip install -U deeptutor
deeptutor init # ports + LLM provider + optional embedding के लिए prompt करता है
deeptutor start # backend + frontend शुरू करता है; terminal खुला रखें
```
`deeptutor init` backend port (default `8001`), frontend port (default `3782`), LLM provider / base URL / API key / model, और Knowledge Base / RAG के लिए optional embedding provider के लिए prompt करता है।
`deeptutor start` के बाद, terminal में print किया गया frontend URL खोलें — default रूप से [http://127.0.0.1:3782](http://127.0.0.1:3782)। backend और frontend दोनों को रोकने के लिए उस terminal में `Ctrl+C` दबाएं। Quick trial के लिए `deeptutor init` छोड़ना ठीक है; app default ports और empty model settings के साथ boot होगा, उन्हें बाद में **Settings → Models** में configure करें।
</details>
<details>
<summary><b>Option 2 — Source से Install करें</b> · checkout के विरुद्ध develop करें</summary>
Checkout के विरुद्ध development के लिए। CI और Docker से match करने के लिए **Python 3.11+** और **Node.js 22 LTS** उपयोग करें।
```bash
git clone https://github.com/HKUDS/DeepTutor.git
cd DeepTutor
# एक venv बनाएं (macOS/Linux). Windows PowerShell:
# py -3.11 -m venv .venv ; .\.venv\Scripts\Activate.ps1
python3 -m venv .venv && source .venv/bin/activate
python -m pip install --upgrade pip
# Backend + frontend deps install करें
python -m pip install -e .
( cd web && npm ci --legacy-peer-deps )
deeptutor init
deeptutor start
```
Source installs local `web/` directory के विरुद्ध Next.js को dev mode में run करते हैं; बाकी सब (config layout, ports, `Ctrl+C` से stop) Option 1 से match करता है।
<details>
<summary><b>Conda environment</b> (<code>venv</code> की बजाय)</summary>
```bash
conda create -n deeptutor python=3.11
conda activate deeptutor
python -m pip install --upgrade pip
```
</details>
<details>
<summary><b>वैकल्पिक install extras</b> — dev / partners / matrix / math-animator</summary>
```bash
pip install -e ".[dev]" # tests/lint tools
pip install -e ".[partners]" # Partner IM channel SDKs + MCP client
pip install -e ".[matrix]" # E2EE/libolm के बिना Matrix channel
pip install -e ".[matrix-e2e]" # Matrix E2EE; libolm चाहिए
pip install -e ".[math-animator]" # Manim addon; LaTeX/ffmpeg/system libs चाहिए
```
</details>
<details>
<summary><b>Frontend dependency tweaks और dev-server troubleshooting</b></summary>
**Frontend dependencies बदलना:** `web/package-lock.json` refresh करने के लिए `npm install --legacy-peer-deps` run करें, फिर `web/package.json` और `web/package-lock.json` दोनों को commit करें।
**Stuck dev server:** अगर `deeptutor start` एक existing frontend report करता है जो respond नहीं कर रहा, तो उस PID को stop करें जो वह print करता है। अगर कोई Next.js process actually नहीं चल रही, तो lock files stale हैं — उन्हें remove करें और retry करें:
```bash
rm -f web/.next/dev/lock web/.next/lock
deeptutor start
```
</details>
</details>
<details>
<summary><b>Option 3 — Docker</b> · एक self-contained container</summary>
पूरे Web app के लिए एक container। GitHub Container Registry पर images:
- `ghcr.io/hkuds/deeptutor:latest` — stable release
- `ghcr.io/hkuds/deeptutor:pre` — pre-release, जब उपलब्ध हो
> podman/rootless/read-only-rootfs deployments और पूरे per-installation guide के लिए [CONTAINERIZATION.md](../../CONTAINERIZATION.md) देखें।
```bash
docker run --rm --name deeptutor \
-p 127.0.0.1:3782:3782 \
-v deeptutor-data:/app/data \
ghcr.io/hkuds/deeptutor:latest
```
> **केवल `3782` publish करना जरूरी है।** Browser exclusively frontend origin से बात करता है; Next.js middleware (`web/proxy.ts`) **container के अंदर** `/api/*` और `/ws/*` को FastAPI backend पर forward करता है। `8001` publish करना (`-p 127.0.0.1:8001:8001`) optional है — केवल curl या scripts से API directly hit करने के लिए उपयोगी।
[http://127.0.0.1:3782](http://127.0.0.1:3782) खोलें। Container पहले boot पर `/app/data/user/settings/*.json` बनाता है; Web Settings page से model providers configure करें। Config, API keys, logs, workspace files, memory, और knowledge bases `deeptutor-data` volume में persist करते हैं।
- **अलग host ports:** प्रत्येक `-p host:container` mapping के left side को बदलें (जैसे `-p 127.0.0.1:8088:3782`)। अगर आप `/app/data/user/settings/system.json` में container-side ports बदलते हैं, तो restart करें और match करने के लिए प्रत्येक mapping के right side को update करें।
- **Detached:** `-d` add करें, फिर follow करने के लिए `docker logs -f deeptutor`, stop करने के लिए `docker stop deeptutor`, नाम reuse करने से पहले `docker rm deeptutor``deeptutor-data` volume आपकी settings और workspace को restarts के पार रखता है।
**Remote Docker / reverse proxy:** browser केवल frontend origin (`:3782`) से बात करता है; in-container Next.js middleware `/api/*` और `/ws/*` को backend server-side पर forward करता है। सामान्य single-container case के लिए API base configure करने की जरूरत नहीं — बस अपना reverse proxy / TLS terminator `:3782` पर point करें। **Split deployment** (backend अलग container/host में) के लिए ही API base चाहिए: `data/user/settings/system.json` में `next_public_api_base` को वह in-network address set करें जो frontend server backend तक पहुंचने के लिए उपयोग करता है (यह server-side read होता है, browser को कभी नहीं भेजा जाता)।
```json
{
"next_public_api_base": "http://backend:8001"
}
```
`next_public_api_base_external` (और इसका alias `public_api_base`) lower-precedence fallbacks के रूप में accept किए जाते हैं। CORS frontend **origins** उपयोग करता है, API URLs नहीं। Auth disabled होने पर, DeepTutor default रूप से normal HTTP/HTTPS browser origins permit करता है। Auth enabled होने पर, exact frontend origins add करें:
```json
{
"cors_origins": ["https://deeptutor.example.com"]
}
```
<details>
<summary><b>Host पर Ollama / LM Studio / llama.cpp / vLLM / Lemonade से Connect करना</b></summary>
Docker के अंदर, `localhost` container itself है, आपका host machine नहीं। Host पर चल रहे model service तक पहुंचने के लिए, host gateway उपयोग करें (recommended):
```bash
docker run --rm --name deeptutor \
-p 127.0.0.1:3782:3782 -p 127.0.0.1:8001:8001 \
--add-host=host.docker.internal:host-gateway \
-v deeptutor-data:/app/data \
ghcr.io/hkuds/deeptutor:latest
```
फिर **Settings → Models** में, provider Base URL को `host.docker.internal` पर point करें:
- Ollama LLM: `http://host.docker.internal:11434/v1`
- Ollama embedding: `http://host.docker.internal:11434/api/embed`
- LM Studio: `http://host.docker.internal:1234/v1`
- llama.cpp: `http://host.docker.internal:8080/v1`
- Lemonade: `http://host.docker.internal:13305/api/v1`
Docker Desktop (macOS/Windows) आमतौर पर `--add-host` के बिना `host.docker.internal` resolve करता है। Linux पर, यह flag modern Docker Engine पर वह hostname बनाने का portable तरीका है।
**Linux alternative — host networking:** `--network=host` add करें और `-p` flags हटाएं। Container host network directly share करता है, इसलिए [http://127.0.0.1:3782](http://127.0.0.1:3782) (या `system.json` में `frontend_port`) खोलें, और host services को normal localhost URLs जैसे `http://127.0.0.1:11434/v1` से reach किया जा सकता है। ध्यान दें कि host networking container ports को host पर directly expose करता है और existing services से conflict हो सकता है — उन्हें loopback पर रखने के लिए `BACKEND_HOST=127.0.0.1` और `FRONTEND_HOST=127.0.0.1` set करें ([CONTAINERIZATION.md](../../CONTAINERIZATION.md) देखें)।
</details>
</details>
<details>
<summary><b>Option 4 — केवल CLI</b> · कोई Web UI नहीं, source checkout से</summary>
जब आपको Web UI की जरूरत न हो। CLI-only package PyPI से नहीं, source checkout से install होता है।
```bash
git clone https://github.com/HKUDS/DeepTutor.git
cd DeepTutor
# एक venv बनाएं (macOS/Linux). Windows PowerShell:
# py -3.11 -m venv .venv-cli ; .\.venv-cli\Scripts\Activate.ps1
python3 -m venv .venv-cli && source .venv-cli/bin/activate
python -m pip install --upgrade pip
python -m pip install -e ./packaging/deeptutor-cli
deeptutor init --cli
deeptutor chat
```
`deeptutor init --cli` पूरे app के समान `data/user/settings/` layout share करता है लेकिन backend/frontend port prompts skip करता है और embeddings को **off** default करता है (अगर आप `deeptutor kb …` या RAG tools उपयोग करने की योजना रखते हैं तो `Yes` चुनें)। यह फिर भी एक complete runtime layout (`system.json`, `auth.json`, `integrations.json`, `model_catalog.json`, `main.yaml`, `agents.yaml`) लिखता है और active LLM provider और model के लिए prompt करता है।
<details>
<summary><b>सामान्य commands</b></summary>
```bash
deeptutor chat # interactive REPL
deeptutor chat --capability deep_solve --tool rag --kb my-kb
deeptutor run chat "Explain Fourier transform"
deeptutor run deep_solve "Solve x^2 = 4" --tool rag --kb my-kb
deeptutor kb create my-kb --doc textbook.pdf
deeptutor memory show
deeptutor config show
```
</details>
Local `deeptutor-cli` install में कोई Web assets या server dependencies नहीं हैं। Source checkout को आसपास रखें — editable install उस पर point करता है। बाद में Web app add करने के लिए, PyPI package (Option 1) install करें और same workspace से `deeptutor init` + `deeptutor start` run करें।
</details>
<details>
<summary><b>Code Execution Sandbox (office skills)</b> · docx / pdf / pptx / xlsx के लिए model-generated code run करना</summary>
Built-in office skills — **docx / pdf / pptx / xlsx** — model द्वारा एक short Python script (`python-docx`, `reportlab`, `openpyxl`, …) लिखकर, इसे `exec` / `code_execution` tools के जरिए run करके, और download URL वापस करके काम करती हैं। वे tools तब mount होते हैं जब एक sandbox backend active होता है, जो **default रूप से** हर deployment shape में होता है:
- **Local (Option 1 / 2) और Docker (Option 3, single container):** एक restricted subprocess sandbox model का code run करता है (locally host पर, या Docker के नीचे container के अंदर — container itself एक isolation boundary है)।
- **docker-compose:** इसके बजाय `DEEPTUTOR_SANDBOX_RUNNER_URL` के जरिए एक hardened, least-privileged **runner sidecar** (`Dockerfile.runner`) पर route किया जाता है — सबसे मजबूत posture, और automatically preferred जब present हो।
Subprocess sandbox `data/user/settings/system.json` में `sandbox_allow_subprocess` setting द्वारा controlled होता है (default `true`)। अपने host पर model-generated code run करना एक real trust decision है — host-side execution को disable करने के लिए इसे `false` set करें (या `DEEPTUTOR_SANDBOX_ALLOW_SUBPROCESS=0` export करें), office skills की files produce करने की क्षमता खोने की कीमत पर।
</details>
<details>
<summary><b>Configuration reference</b> — <code>data/user/settings/</code> के नीचे config files (JSON/YAML)</summary>
`data/user/settings/` के नीचे सब कुछ plain JSON/YAML है। Browser में **Settings** page recommended editor है।
| File | उद्देश्य |
|:---|:---|
| `model_catalog.json` | LLM, embedding, और search provider profiles; API keys; active models |
| `system.json` | Backend/frontend ports, public API base, CORS, SSL verification, attachment directory |
| `auth.json` | Optional auth toggle, username, password hash, token/cookie settings |
| `integrations.json` | Optional PocketBase और sidecar integration settings |
| `interface.json` | UI language / theme / sidebar preferences |
| `main.yaml` | Runtime behavior defaults और path injection |
| `agents.yaml` | Capability/tool temperature और token settings |
Project-root `.env` application config file के रूप में **नहीं** पढ़ा जाता। Minimal model setup के लिए, **Settings → Models** खोलें, एक LLM profile (Base URL / API key / model name) add करें, और save करें। Embedding profile केवल तभी add करें जब आप Knowledge Base / RAG features उपयोग करने की योजना रखते हों।
</details>
## 📖 DeepTutor को एक्सप्लोर करें
दैनिक उपयोग की मुख्य surfaces से शुरू करें: Chat, Partners, My Agents, Co-Writer, Book, Knowledge Center, Learning Space, Memory, और Settings। फिर tour साझा, isolated workspaces के लिए Multi-User deployments को cover करता है।
<div align="center">
<img src="../../assets/figs/web-1.4.6+/OVERVIEW.png" alt="DeepTutor home — sidebar में हर surface के साथ Chat workspace" width="900">
</div>
<details>
<summary><b>🏗️ System architecture</b></summary>
<div align="center">
<img src="../../assets/figs/system/system%20architecture.png" alt="DeepTutor system architecture" width="900">
</div>
</details>
<details>
<summary><b>💬 Chat — वह Agent Loop जो आप Actually उपयोग करते हैं</b></summary>
Chat default capability है और जहां से अधिकांश काम शुरू होता है। एक single thread normally बात कर सकता है, tools call कर सकता है, selected knowledge bases में खुद को ground कर सकता है, attachments पढ़ सकता है, images generate कर सकता है, subagents से consult कर सकता है, notebook records लिख सकता है, और turns के पार same context के साथ जारी रह सकता है।
<div align="center">
<img src="../../assets/figs/web-1.4.6+/home/00-overview.png" alt="DeepTutor chat workspace" width="900">
</div>
Loop जानबूझकर simple है: model rounds में सोचता है, जब उपयोगी हो tools call करता है, results observe करता है, और tool-free message के साथ finish करता है। `ask_user` special है — guess करने की बजाय, agent turn pause कर सकता है, एक structured clarifying question पूछ सकता है, और आपके जवाब देने के बाद resume कर सकता है।
<div align="center">
<img src="../../assets/figs/system/chat-agent-loop.png" alt="DeepTutor chat agent loop" width="900">
</div>
User-toggleable tools हैं `brainstorm`, `web_search`, `paper_search`, `reason`, और `geogebra_analysis` — साथ ही `imagegen` और `videogen` जब आप matching generation model configure करें। Contextual tools जैसे `rag`, `read_source`, `read_memory`, `write_memory`, `read_skill`, `load_tools`, `exec`, `web_fetch`, `ask_user`, `list_notebook`, `write_note`, `github`, और `consult_subagent` तब automatically mount होते हैं जब turn के पास सही context हो।
Context दो प्रकार की होती है: **sticky session context** (subagent, knowledge bases, persona, model, voice) composer toolbar पर रहती है और turns के पार persist करती है; **एक-बार references** (files, chat history, books, notebooks, question bank, imported agents) एक single turn के लिए `+` menu से आते हैं।
Chat deeper capabilities के लिए launch point भी है: **Quiz** question generation के लिए, **Research** cited reports के लिए, **Visualize** charts / diagrams / animations के लिए, और — *More Capabilities* के नीचे — **Solve** worked reasoning के लिए और **Mastery Path** learning-plan flows के लिए।
</details>
<details>
<summary><b>🤝 Partner — Same Brain पर Persistent Companions</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/partners/00-partners%20overview.png" alt="DeepTutor partners workspace" width="900">
</div>
Partners अपनी soul, model policy, library, memory, और channels वाले persistent companions हैं। वे एक अलग bot engine नहीं हैं: हर inbound web या IM message partner-scoped workspace के अंदर एक normal `ChatOrchestrator` turn बन जाता है। एक partner "एक chat है जिसकी personality और phone number है।"
<div align="center">
<img src="../../assets/figs/system/partners-architecture.png" alt="DeepTutor partners architecture" width="900">
</div>
हर partner के पास एक `SOUL.md`, model selection, channels, tool policy, और assigned library है। Knowledge bases, skills, और notebooks `data/partners/<id>/workspace/` में copy होते हैं, इसलिए same RAG, skill, notebook, और memory tools special cases के बिना काम करते हैं। एक partner अपने owner की memory पढ़ता है लेकिन केवल अपनी memory में लिखता है।
<div align="center">
<img src="../../assets/figs/web-1.4.6+/partners/02-IM%20config%20for%20each%20partner.png" alt="प्रत्येक partner के लिए per-partner IM channel configuration" width="900">
</div>
Channel layer schema-driven है और installed extras और configured credentials के आधार पर Feishu, Telegram, Slack, Discord, DingTalk, QQ/NapCat, WeCom, WhatsApp, Zulip, Mattermost, Matrix, Mochat, और Microsoft Teams जैसे IM platforms से connect हो सकती है। एक partner को subagent के रूप में भी connect किया जा सकता है और normal chat turn से consult किया जा सकता है — नीचे **My Agents** देखें।
</details>
<details>
<summary><b>🧑‍🚀 My Agents — दूसरे Agents को Consult और Import करें</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/myagents/00-overview.png" alt="DeepTutor My Agents workspace" width="900">
</div>
My Agents दूसरे agents को DeepTutor के लिए context बनाता है, और दो अलग काम करता है। **लाइव एजेंट connect करें** — आपकी machine पर Claude Code या Codex CLI, या आपके Partners में से एक — और इसे chat turn के अंदर से consult करें: DeepTutor actually दूसरे agent को *run* करता है और इसके काम को `consult_subagent` tool के जरिए Activity panel में stream करता है। इसे Agent chip से select करें (या `@` type करें), और set करें कि consult कितने rounds ले सकता है।
<div align="center">
<img src="../../assets/figs/web-1.4.6+/home/08-subagent%20demo%20with%20claude%20code.png" alt="Claude Code subagent को live consult करना" width="900">
</div>
**पिछली conversations import करें** — अपनी existing Claude Code और Codex history को named, searchable, resumable agents के रूप में bring in करें। Import करने के लिए कौन से days लेने हैं चुनें; refreshing उन्हें re-sync करता है। किसी भी chat turn से imported conversation को `+` → My Agents के जरिए reference करें, और DeepTutor इसे एक third-party transcript के रूप में पढ़ता है — यह उनकी conversation रहती है, DeepTutor की अपनी आवाज नहीं।
</details>
<details>
<summary><b>✍️ Co-Writer — Selection-Aware Markdown Drafting</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/co-writer/00-overview.png" alt="DeepTutor Co-Writer workspace" width="900">
</div>
Co-Writer reports, tutorials, notes, और long-form learning artifacts के लिए एक split-view Markdown workspace है। Documents autosave होते हैं और live preview render करते हैं (KaTeX math, diagram fences), और जब draft reusable context बन जाए तो notebooks में save किए जा सकते हैं।
<div align="center">
<img src="../../assets/figs/web-1.4.6+/co-writer/01-edit%20panel.png" alt="Co-Writer editor with live preview" width="900">
</div>
इसका defining idea **surgical editing** है: एक span select करें और DeepTutor से rewrite, expand, या shorten करने के लिए कहें। Edit agent change को एक knowledge base या web evidence में ground कर सकता है, अपने tool calls का trace रखता है, और हर change को accept/reject diff के रूप में दिखाता है — इसलिए कुछ भी land नहीं होता जब तक आप approve नहीं करते।
</details>
<details>
<summary><b>📖 Book — आपकी सामग्री से Living Books</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/book/00-book_overview.png" alt="DeepTutor book library" width="900">
</div>
Book selected sources को एक interactive **living book** में बदलता है — एक static PDF नहीं, बल्कि typed blocks से बना एक reading environment। एक book knowledge bases, notebooks, question banks, या chat history से शुरू हो सकती है; creation flow content generate होने से पहले एक chapter outline propose करता है, इसलिए आप blind one-shot output accept करने की बजाय shape review करते हैं।
<p align="center">
<img src="../../assets/figs/web-1.4.6+/book/01-book-demo-quiz%20card.png" alt="Book quiz block" width="31%">
&nbsp;
<img src="../../assets/figs/web-1.4.6+/book/02-book-demo-manim%20video.png" alt="Book Manim animation block" width="31%">
&nbsp;
<img src="../../assets/figs/web-1.4.6+/book/03-book-demo%20interactive%20module.png" alt="Book interactive widget block" width="31%">
</p>
हर chapter typed blocks में compile होती है — text, callouts, quizzes, flash cards, timelines, code, figures, interactive HTML, animations, concept graphs, deep dives, और user notes — और हर page का अपना Page Chat है। Blocks editable हैं: chapter rewrite किए बिना किसी block को insert, move, regenerate, या उसका type switch करें। Maintenance commands जैसे `deeptutor book health` और `deeptutor book refresh-fingerprints` तब detect करने में मदद करते हैं जब source knowledge compiled pages से drift हो गया हो।
</details>
<details>
<summary><b>📚 Knowledge Center — Multi-Engine RAG Libraries</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/knowledge/00-overview.png" alt="DeepTutor Knowledge Center" width="900">
</div>
Knowledge bases RAG के पीछे document collections हैं — वे Chat turns, Co-Writer edits, Book generation, और Partner conversations को ground करते हैं। जो distinctive है वह है **retrieval engines का choice**: **LlamaIndex** (default, local vector + BM25), **PageIndex** (hosted, reasoning retrieval with page-level citations), **GraphRAG** और **LightRAG** (knowledge-graph retrieval), **LightRAG Server** (retrieval एक external LightRAG instance पर offload किया जाता है जिसे आप HTTP पर connect करते हैं), या एक linked **Obsidian** vault जिसे tutor in-place पढ़ता और लिखता है। हर KB एक engine से bound होती है।
<div align="center">
<img src="../../assets/figs/web-1.4.6+/knowledge/01-create%20knowledge%20base.png" alt="एक knowledge base बनाएं" width="900">
</div>
KB बनाते समय, आप either **नया create** करते हैं (documents upload करें और fresh index build करें) या **existing link** करते हैं (कहीं और बना index reuse करें, re-index के बिना in-place पढ़ें)। Re-indexing एक नई flat `version-N` directory लिखता है और prior ones रखता है, इसलिए एक working index rebuild के दौरान कभी destroy नहीं होता। एक single document को **error**-state base से भी remove किया जा सकता है — पूरी delete-and-rebuild के बिना parse होने में failed हुई file को drop करना। Document parsing — Text-only, MinerU, Docling, markitdown, या PyMuPDF4LLM — **Settings → Knowledge Base** में choose किया जाता है, local model downloads default रूप से off हैं। CLI lifecycle को `deeptutor kb list`, `info`, `create`, `add`, `search`, `set-default`, और `delete` से mirror करता है।
</details>
<details>
<summary><b>🌐 Learning Space — Skills, Personas, और Reusable Context</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/learning-space/00-overview.png" alt="DeepTutor Learning Space hub" width="900">
</div>
Learning Space library और personalization layer है — वह जगह जहां persist होने वाली चीजें रहती हैं। **Conversations & Materials** में आपका chat history, notebooks, और एक question bank है (हर saved question आपका जवाब, reference answer, और एक explanation रखता है)। **Personalization** में mastery paths, personas (behavior presets जैसे *peer*, *research-assistant*, *teacher*), और skills (`SKILL.md` playbooks जिन्हें model on-demand पढ़ता है) हैं। यहां सब कुछ Chat, Partners, Co-Writer, और Book से reuse किया जा सकता है।
<div align="center">
<img src="../../assets/figs/web-1.4.6+/learning-space/07-%20download%20skills%20from%20eduhub.png" alt="EduHub से skills import करें" width="900">
</div>
आपको हर skill खुद नहीं लिखनी है — **Import from EduHub** community catalog browse करता है और एक security gate के जरिए directly आपकी library में skill download करता है (देखें [Ecosystem](#-इकोसिस्टम--eduhub-और-skills-community))।
</details>
<details>
<summary><b>🧠 Memory — Inspectable Personalization</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/memory/00-overview.png" alt="DeepTutor memory overview" width="900">
</div>
Memory एक file-backed, three-layer system है जिसे आप पढ़, curate, और audit कर सकते हैं — जानबूझकर एक hidden vector store नहीं। **L1** workspace mirror plus एक append-only event trace (`trace/<surface>/<date>.jsonl`) है; **L2** per-surface curated facts (`L2/<surface>.md`) है; **L3** cross-surface synthesis (`L3/<profile|recent|scope|preferences>.md`) है। क्योंकि L2 L1 cite करता है और L3 L2 cite करता है, आपके profile में कुछ भी unaccountable नहीं है।
<div align="center">
<img src="../../assets/figs/web-1.4.6+/memory/01-3%20layer%20memory%20graph.png" alt="DeepTutor memory graph" width="900">
</div>
Memory Graph पूरा pyramid दिखाता है — L3 synthesis centre में, L2 middle ring में, L1 traces outside में — इसलिए आप किसी भी synthesized claim को उसके पीछे exact raw event तक trace कर सकते हैं। Memory `chat`, `notebook`, `quiz`, `kb`, `book`, partner, और `cowriter` surfaces पर track किया जाता है; consolidator के Update / Audit / Dedup budgets **Settings → Memory** में tune किए जाते हैं।
</details>
<details>
<summary><b>⚙️ Settings — एक Control Plane</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/settings/00-setting%20overview.png" alt="DeepTutor settings hub" width="900">
</div>
Settings operational control plane है, एक live status strip (Backend, LLM, Embedding, Search) और प्रत्येक area के लिए एक card के साथ: **Appearance** (theme + UI language), **Network** (API base, ports, CORS), **Models** (LLM, Embedding, Search, Text-to-Speech, Speech-to-Text, Image Generation, Video Generation), **Knowledge Base** (document parsing engine), **Chat** (tools, MCP servers, per-capability parameters), **Partners & Agents** (वे subagents जिन्हें आप turn से consult कर सकते हैं), और **Memory** (consolidator के budgets)।
<div align="center">
<img src="../../assets/figs/web-1.4.6+/settings/01-appearance%20settings.png" alt="DeepTutor appearance settings and themes" width="900">
</div>
अधिकांश sections एक draft-and-apply flow उपयोग करते हैं, इसलिए आप provider को commit करने से पहले test कर सकते हैं। चार themes box में आते हैं — Default, Cream, Dark, और Glass। Project-root `.env` files जानबूझकर ignored हैं; runtime configuration `data/user/settings/*.json` के नीचे रहती है जब तक कि `DEEPTUTOR_HOME` या `deeptutor start --home` app को कहीं और point न करे।
</details>
<details>
<summary><b>👥 Multi-User — Shared Deployments</b> · optional auth, isolated per-user workspaces</summary>
Authentication **default रूप से बंद** है — DeepTutor single-user चलता है। इसे on करें और एक `data/` tree एक admin workspace, isolated per-user workspaces, और partner workspaces को side by side host करती है:
```text
data/
├── user/ # Admin workspace + global settings
├── users/<uid>/ # Per-user scope: chat history, memory, notebooks, KBs
├── partners/<id>/workspace/ # Partner (synthetic-user) scope
└── system/ # auth/users.json · grants/<uid>.json · audit/usage.jsonl
```
**पहला registered user admin बनता है** और model catalogs, provider credentials, shared knowledge bases, skills, और per-user grants own करता है। बाकी सभी को isolated workspace और redacted Settings page मिलती है — admin-assigned models, KBs, और skills scoped, read-only options के रूप में दिखाई देते हैं, कभी raw API keys के रूप में नहीं।
**Enable करें:** `data/user/settings/auth.json` में auth on करें, `deeptutor start` restart करें, `/register` पर पहला admin register करें, फिर `/admin/users` से users add करें और grants के जरिए models, KBs, skills, Partners, tool/MCP policy, और code-execution access assign करें।
> PocketBase single-user integration रहता है — multi-user deployments के लिए `integrations.pocketbase_url` blank रखें जब तक आपने external user store wire up नहीं किया हो।
</details>
## ⌨️ DeepTutor CLI — एजेंट-नेटिव इंटरफेस
एक `deeptutor` binary, दो तरीके से: terminal में रहने वालों के लिए interactive **REPL**, और DeepTutor को tool के रूप में drive करने वाले दूसरे agents के लिए structured **JSON**। दोनों तरफ same capabilities, tools, और knowledge bases।
<details>
<summary><b>खुद drive करें</b></summary>
`deeptutor chat` एक interactive REPL खोलता है; `deeptutor run <capability> "<message>"` एक single turn fire करके exit करता है। दोनों same `--capability`, `--tool`, `--kb`, और `--config` flags बोलते हैं।
```bash
deeptutor chat # interactive REPL
deeptutor chat --capability deep_solve --kb my-kb --tool rag
deeptutor run chat "Explain the Fourier transform" --tool rag --kb textbook
deeptutor run deep_research "Survey 2026 papers on RAG" \
--config mode=report --config depth=standard
```
Web app जो कुछ भी करता है वह यहां भी है — knowledge bases (`kb`), sessions (`session`), partners (`partner`), skills (`skill`), notebooks, memory, और config। नीचे पूरी list।
</details>
<details>
<summary><b>किसी agent को drive करने दें</b></summary>
DeepTutor *दूसरे agent द्वारा operated* होने के लिए built है। किसी भी `run` में `--format json` add करें और हर turn **NDJSON — एक event per line** stream करता है (`content`, `tool_call`, `tool_result`, `done`, …), हर line `session_id` के साथ tagged। Runs headless-safe हैं: बिना TTY के `ask_user` pause automatically empty reply से resolve होता है बजाय hang करने के।
```bash
# One shot, machine-readable
deeptutor run deep_solve "Find d/dx[sin(x^2)]" --tool reason --format json
# एक stateful session में turns chain करें — id capture करें, reuse करें
SID=$(deeptutor run deep_research "Survey 2026 papers on RAG" \
--config mode=report --config depth=standard --format json \
| jq -r 'select(.type=="done").session_id')
deeptutor run deep_question "Quiz me on that survey" --session "$SID" --format json
```
Repo एक root [`SKILL.md`](../../SKILL.md) ship करता है — एक ~150-line handover doc जो किसी भी tool-using LLM को एक read में पूरा surface सिखाता है। इसे Claude Code, Codex, या OpenCode को दें (वे `SKILL.md` automatically pick up करते हैं), या `deeptutor run` को LangChain / AutoGen loop में एक tool के रूप में wrap करें। पूरे recipes: [Agent Handoff](https://deeptutor.info/docs/cli/agent-handoff/)।
</details>
<details>
<summary><b>Command reference</b></summary>
| Command | विवरण |
|:---|:---|
| `deeptutor init` | Current workspace के लिए `data/user/settings` create या update करें |
| `deeptutor start [--home PATH]` | Backend + frontend को एक साथ launch करें |
| `deeptutor serve [--port PORT]` | केवल FastAPI backend start करें |
| `deeptutor run <capability> <message>` | एक single capability turn run करें (`chat`, `deep_solve`, `deep_question`, `deep_research`, `visualize`, `math_animator`, `mastery_path`); NDJSON output के लिए `--format json` add करें |
| `deeptutor chat` | capability, tool, KB, notebook, और history controls के साथ interactive REPL |
| `deeptutor partner list/create/start/stop` | IM-connected partners manage करें |
| `deeptutor kb list/info/create/add/search/set-default/delete` | LlamaIndex knowledge bases manage करें |
| `deeptutor skill search/install/list/remove/login/logout/publish/update` | Skills manage करें, hubs से install करें, और अपनी खुद publish करें (default `eduhub:<slug>`, Ecosystem देखें) |
| `deeptutor memory show/clear` | L2/L3 memory docs inspect करें या L1/all memory clear करें |
| `deeptutor session list/show/open/rename/delete` | Shared sessions manage करें |
| `deeptutor notebook list/create/show/add-md/replace-md/remove-record` | Markdown files से notebooks manage करें |
| `deeptutor book list/health/refresh-fingerprints` | Books inspect करें और source fingerprints refresh करें |
| `deeptutor plugin list/info` | Registered tools और capabilities inspect करें |
| `deeptutor config show` | Configuration summary print करें |
| `deeptutor provider login <provider>` | Provider auth (`openai-codex` OAuth login; `github-copilot` existing Copilot auth session validate करता है) |
</details>
<details>
<summary><b>CLI-only distribution</b></summary>
CLI-only package `packaging/deeptutor-cli` में रहता है। इस checkout में, इसे source से install करें:
```bash
python -m pip install -e ./packaging/deeptutor-cli
```
यह अभी PyPI पर publish नहीं है, इसलिए main [शुरू करें](#-शुरू-करें) section source-install path रखता है।
</details>
## 🧩 इकोसिस्टम — EduHub और Skills Community
DeepTutor skills open **Agent-Skills** format उपयोग करती हैं — एक `SKILL.md` playbook (YAML frontmatter + Markdown) और optional reference files के साथ एक folder। इसमें DeepTutor-specific कुछ नहीं है, इसलिए format बोलने वाली कोई भी registry आपकी library के लिए एक source बन जाती है। DeepTutor **[EduHub](https://eduhub.deeptutor.info/)** के साथ ship होता है — हमारी अपनी education-focused skill registry — default hub के रूप में built in।
<details>
<summary><b>EduHub — DeepTutor का skill ecosystem</b></summary>
[**EduHub**](https://eduhub.deeptutor.info/) वह community hub है जिसे DeepTutor ने teaching-oriented agent skills share करने के लिए launch किया — Socratic tutors, flashcard builders, essay feedback, exam blueprints, concept explainers, और बहुत कुछ। यह DeepTutor में built in है, इसलिए configure करने की कोई जरूरत नहीं: एक bare slug या `eduhub:` prefix इसे resolve करता है।
**ढूंढें और install करें** — browser में, catalog browse करने और directly आपकी library में skill download करने के लिए **Learning Space → Skills → Import from EduHub** खोलें। Terminal से:
```bash
deeptutor skill search "socratic tutor" # EduHub search करें (default hub)
deeptutor skill install socratic-tutor # fetch → verify → register
deeptutor skill install eduhub:socratic-tutor@1.2.0 # hub और version pin करें
deeptutor skill list # उनके hub provenance के साथ local skills
```
**अपनी खुद publish करें** — एक `SKILL.md` package करें और community के साथ share करें:
```bash
deeptutor skill login # EduHub पर browser sign-in
deeptutor skill publish ./my-skill # interactive: track + tags चुनें, फिर upload
deeptutor skill update # roll back या नया version release करें
```
EduHub एक standalone, ClawHub-compatible registry भी है, इसलिए DeepTutor नहीं होने वाले agents (Claude Code, Codex, …) इसे `eduhub` CLI के जरिए directly use कर सकते हैं — `npx eduhub install socratic-tutor`
</details>
<details>
<summary><b>Import safety gate</b></summary>
Source चाहे जो भी हो, हर import आपके workspace को touch करने से पहले **same safety gate** से गुजरता है:
- registry का **security verdict** पहले check होता है — flagged packages refuse किए जाते हैं जब तक आप `--allow-unverified` pass नहीं करते;
- archives defensively extract होते हैं (zip-slip / zip-bomb guards) text/script **suffix whitelist** के पीछे, इसलिए binaries workspace में कभी नहीं आते;
- frontmatter DeepTutor के schema में normalize होता है और `always:` **stripped** होता है, इसलिए एक downloaded skill खुद को हर system prompt में force नहीं कर सकती;
- provenance — hub, version, verdict, और install time — audits और updates के लिए `.hub-lock.json` में लिखा जाता है।
Multi-user deployments में, installing admin-only है: एक नई skill admin catalog में land करती है और दूसरे users को invisible रहती है जब तक grant assign नहीं करता, इसलिए admin इसे roll out करने से पहले vet कर सकता है।
</details>
<details>
<summary><b>ClawHub के साथ भी compatible</b></summary>
क्योंकि DeepTutor open Agent-Skills format बोलता है, **[ClawHub](https://clawhub.ai/)** भी एक first-class source है — यह EduHub के साथ built in है। इसे hub prefix से चुनें:
```bash
deeptutor skill search "git release notes" --hub clawhub
deeptutor skill install clawhub:git-release-notes@1.0.1
```
`settings/skill_hubs.json` में और registries add करें: एक `type: "clawhub"` entry किसी भी compatible HTTP API पर point करती है (EduHub और ClawHub दोनों इसे बोलते हैं), `type: "command"` जो fetch CLI एक registry ship करती है उसे wrap करता है, और `"default"` bare slugs के लिए उपयोग होने वाला hub choose करता है। सभी same import gate feed करते हैं।
</details>
## 🌐 समुदाय
### 📮 संपर्क
DeepTutor [HKUDS](https://github.com/HKUDS) Group के अंदर [Bingxi Zhao](https://github.com/pancacake) द्वारा lead किया जाने वाला एक open-source project है, और यह **पूरी तरह open-source रूप में**, community के साथ मिलकर बनाया जाता है। अब तक, हमारे पास किसी भी प्रकार के **paid online products नहीं** हैं। discussions, ideas, या collaboration के लिए **bingxizhao39@gmail.com** पर contact करें।
### 🙏 आभार
[**Chao Huang**](https://sites.google.com/view/chaoh), Data Intelligence Lab @ HKU के director, और उनके warm support के लिए हमारे HKUDS labmates — विशेष रूप से [**Jiahao Zhang**](https://github.com/zzhtx258), [**Zirui Guo**](https://github.com/LarFii), और [**Xubin Ren**](https://github.com/Re-bin) — के प्रति हार्दिक आभार। हम **open-source community** के प्रति भी गहराई से आभारी हैं: आपके stars, issues, pull requests, और discussions हर एक दिन DeepTutor को आकार देते हैं।
DeepTutor outstanding open-source projects के कंधों पर खड़ा है जिन्होंने हमें tools और inspiration दोनों दिए:
| Project | भूमिका / Inspiration |
|:---|:---|
| [**LlamaIndex**](https://github.com/run-llama/llama_index) | RAG pipeline और document-indexing backbone |
| [**nanobot**](https://github.com/HKUDS/nanobot) | Ultra-lightweight agent engine जिसने original TutorBot को powered किया *(HKUDS)* |
| [**LightRAG**](https://github.com/HKUDS/LightRAG) | Simple & fast RAG *(HKUDS)* |
| [**AutoAgent**](https://github.com/HKUDS/AutoAgent) | Zero-code agent framework *(HKUDS)* |
| [**AI-Researcher**](https://github.com/HKUDS/AI-Researcher) | Automated research pipeline *(HKUDS)* |
| [**OpenClaw**](https://github.com/openclaw/openclaw) | ClawHub के पीछे open agent gateway और skill ecosystem |
| [**Codex**](https://github.com/openai/codex) | Agent-native coding CLI जिसने हमारे CLI workflow को inspire किया |
| [**Claude Code**](https://github.com/anthropics/claude-code) | Agentic coding CLI जिसने DeepTutor agent loop को inspire किया |
| [**ManimCat**](https://github.com/Wing900/ManimCat) | Math Animator के लिए AI-driven math animation generation |
### 🗺️ Roadmap और योगदान
हम चाहते हैं कि DeepTutor iterate और improve करता रहे — और अंततः open-source community को एक gift बने। हमारा [**roadmap**](https://github.com/HKUDS/DeepTutor/issues/498) continuously update होता है; वहां items पर vote करें या नए propose करें। अगर आप contribute करना चाहते हैं, तो branching strategy, coding standards, और शुरू करने के तरीके के लिए [**Contributing Guide**](../../CONTRIBUTING.md) देखें।
<div align="center">
हम आशा करते हैं कि DeepTutor community के लिए एक उपहार बने। 🎁
<a href="https://github.com/HKUDS/DeepTutor/graphs/contributors">
<img src="https://contrib.rocks/image?repo=HKUDS/DeepTutor&max=999" alt="Contributors" />
</a>
</div>
<div align="center">
<a href="https://www.star-history.com/#HKUDS/DeepTutor&type=timeline&legend=top-left">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=HKUDS/DeepTutor&type=timeline&theme=dark&legend=top-left" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=HKUDS/DeepTutor&type=timeline&legend=top-left" />
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=HKUDS/DeepTutor&type=timeline&legend=top-left" />
</picture>
</a>
</div>
<p align="center">
<a href="https://www.star-history.com/hkuds/deeptutor">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/badge?repo=HKUDS/DeepTutor&theme=dark" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/badge?repo=HKUDS/DeepTutor" />
<img alt="Star History Rank" src="https://api.star-history.com/badge?repo=HKUDS/DeepTutor" />
</picture>
</a>
</p>
<div align="center">
[Apache License 2.0](../../LICENSE) के तहत licensed।
<p>
<img src="https://visitor-badge.laobi.icu/badge?page_id=HKUDS.DeepTutor&style=for-the-badge&color=00d4ff" alt="Views">
</p>
</div>
</content>
</invoke>
+707
View File
@@ -0,0 +1,707 @@
<div align="center">
<p align="center"><img src="../../assets/figs/logo/logo.png" alt="DeepTutor ロゴ" height="56" style="vertical-align: middle;">&nbsp;<img src="../../assets/figs/logo/banner.png" alt="DeepTutor" height="48" style="vertical-align: middle;"></p>
# DeepTutor:生涯にわたるパーソナライズド個別指導
<p align="center">
<a href="https://deeptutor.info" target="_blank"><img alt="Docs — deeptutor.info" src="https://img.shields.io/badge/Docs-deeptutor.info%20%E2%86%97-0A0A0A?style=for-the-badge&labelColor=F5F5F4" height="36"></a>
</p>
<p align="center">
<a href="https://trendshift.io/repositories/17099?utm_source=repository-badge&amp;utm_medium=badge&amp;utm_campaign=badge-repository-17099" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/repositories/17099" alt="HKUDS%2FDeepTutor | Trendshift" width="250" height="55"/></a>&nbsp;
<a href="https://trendshift.io/repositories/17099?utm_source=trendshift-badge&amp;utm_medium=badge&amp;utm_campaign=badge-trendshift-17099" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/17099/daily" alt="HKUDS%2FDeepTutor | Trendshift" width="250" height="55"/></a>&nbsp;
<a href="https://trendshift.io/repositories/17099?utm_source=trendshift-badge&amp;utm_medium=badge&amp;utm_campaign=badge-trendshift-17099" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/17099/weekly?language=Python" alt="HKUDS%2FDeepTutor | Trendshift" width="250" height="55"/></a>
</p>
<p align="center">
<a href="../../README.md"><img alt="English" height="40" src="https://img.shields.io/badge/English-CDCFD4"></a>&nbsp;
<a href="README_CN.md"><img alt="简体中文" height="40" src="https://img.shields.io/badge/简体中文-CDCFD4"></a>&nbsp;
<a href="README_JA.md"><img alt="日本語" height="40" src="https://img.shields.io/badge/日本語-BCDCF7"></a>&nbsp;
<a href="README_ES.md"><img alt="Español" height="40" src="https://img.shields.io/badge/Español-CDCFD4"></a>&nbsp;
<a href="README_FR.md"><img alt="Français" height="40" src="https://img.shields.io/badge/Français-CDCFD4"></a>&nbsp;
<a href="README_AR.md"><img alt="Arabic" height="40" src="https://img.shields.io/badge/Arabic-CDCFD4"></a>&nbsp;
<a href="README_RU.md"><img alt="Русский" height="40" src="https://img.shields.io/badge/Русский-CDCFD4"></a>&nbsp;
<a href="README_HI.md"><img alt="Hindi" height="40" src="https://img.shields.io/badge/Hindi-CDCFD4"></a>&nbsp;
<a href="README_PT.md"><img alt="Português" height="40" src="https://img.shields.io/badge/Português-CDCFD4"></a>&nbsp;
<a href="README_TH.md"><img alt="Thai" height="40" src="https://img.shields.io/badge/Thai-CDCFD4"></a>&nbsp;
<a href="README_PL.md"><img alt="Polski" height="40" src="https://img.shields.io/badge/Polski-CDCFD4"></a>
</p>
[![Python 3.11+](https://img.shields.io/badge/Python-3.11%2B-3776AB?style=flat-square&logo=python&logoColor=white)](https://www.python.org/downloads/)
[![Next.js 16](https://img.shields.io/badge/Next.js-16-000000?style=flat-square&logo=next.js&logoColor=white)](https://nextjs.org/)
[![License](https://img.shields.io/badge/License-Apache_2.0-blue?style=flat-square)](../../LICENSE)
[![GitHub release](https://img.shields.io/github/v/release/HKUDS/DeepTutor?style=flat-square&color=brightgreen)](https://github.com/HKUDS/DeepTutor/releases)
[![arXiv](https://img.shields.io/badge/arXiv-2604.26962-b31b1b?style=flat-square&logo=arxiv&logoColor=white)](https://arxiv.org/abs/2604.26962)
[![Discord](https://img.shields.io/badge/Discord-Community-5865F2?style=flat-square&logo=discord&logoColor=white)](https://discord.gg/eRsjPgMU4t)
[![Feishu](https://img.shields.io/badge/Feishu-Group-00D4AA?style=flat-square&logo=feishu&logoColor=white)](../../Communication.md)
[![WeChat](https://img.shields.io/badge/WeChat-Group-07C160?style=flat-square&logo=wechat&logoColor=white)](https://github.com/HKUDS/DeepTutor/issues/78)
[機能](#-主な機能) · [はじめに](#-はじめに) · [探索](#-deeptuitorを探索する) · [CLI](#%EF%B8%8F-deeptutor-cli--エージェントネイティブインターフェース) · [エコシステム](#-エコシステム--eduhubとスキルコミュニティ) · [コミュニティ](#-コミュニティ)
</div>
---
> 🤝 **あらゆる形の貢献を歓迎します!** [`ロードマップ`](https://github.com/HKUDS/DeepTutor/issues/498) でアイテムに投票したり新しいアイデアを提案したりできます。ブランチ戦略、コーディング基準、参加方法については [貢献ガイド](../../CONTRIBUTING.md) をご覧ください。
### 📰 ニュース
- **2026-05-22** 🌐 公式ドキュメントサイトが [**deeptutor.info**](https://deeptutor.info/) で公開 — ガイド、リファレンス、機能ツアーを一か所に。
- **2026-04-19** 🎉 111日間で20kスター達成!真にパーソナライズされたインテリジェント個別指導に向けた支援に感謝します。
- **2026-04-10** 📄 arXivに論文を公開 — DeepTutorの設計とアイデアについては[プレプリント](https://arxiv.org/abs/2604.26962)をご覧ください。
- **2026-02-06** 🚀 わずか39日間で10kスター達成!素晴らしいコミュニティに心から感謝します。
- **2026-01-01** 🎊 あけましておめでとうございます![Discord](https://discord.gg/eRsjPgMU4t)、[WeChat](https://github.com/HKUDS/DeepTutor/issues/78)、または[Discussions](https://github.com/HKUDS/DeepTutor/discussions)に参加して一緒にDeepTutorを形作りましょう。
- **2025-12-29** 🎓 DeepTutor正式リリース!
## ✨ 主な機能
DeepTutorは、個別指導、問題解決、クイズ生成、研究、ビジュアライゼーション、習熟度練習を1つの拡張可能なシステムに統合したエージェントネイティブな学習ワークスペースです。
- **すべてのモードで1つのランタイム** — Chat、Quiz、Research、Visualize、Solve、Mastery Pathが同じエージェントループで実行されるため、エンジンではなく目的を切り替えます。コンテキストは学習者とともに移動します。
- **接続された学習コンテキスト** — 知識ベース、本、Co-Writerの下書き、ノートブック、問題バンク、ペルソナ、Memoryが孤立したツールに閉じ込められることなく、すべてのワークフローで利用可能です。
- **サブエージェントとPartners** — 任意のターンからライブのClaude Code、Codex、またはPartnerに相談(または過去の会話をインポート)し、同じブレインで永続的なIMコンパニオンを実行します。
- **マルチエンジン知識** — LlamaIndex、PageIndex、GraphRAG、LightRAG、またはリンクされたObsidianボールトにまたがるバージョン管理されたRAGライブラリ(プラグ可能なドキュメント解析付き)。
- **拡張可能なツールとスキル** — 組み込みツール、MCPサーバー、画像/ビデオ/音声生成モデル、EduHubからインストール可能なコミュニティスキル。
- **検査可能なメモリ** — L1トレース、L2サーフェスサマリー、L3合成によりパーソナライズが可視化・編集可能となり、Memory Graphですべての主張を証拠まで追跡できます。
---
## 🚀 はじめに
DeepTutorは4つのインストールパスを提供しています。すべてのパスは同じワークスペースレイアウトを共有します。設定はデプロイするディレクトリ下の`data/user/settings/`に保存されます(明示的に設定した場合は`DEEPTUTOR_HOME`/`deeptutor start --home`の下)。完全なアプリの場合は **ワークスペースディレクトリの選択 → インストール → `deeptutor init` → `deeptutor start`** がお勧めのフローです。
<details>
<summary><b>オプション1 — PyPIからインストール</b> · クローン不要のフルローカルWebアプリ + CLI</summary>
クローン不要のフルローカルWebアプリ + CLI。**Python 3.11+** とPATH上の**Node.js 20+**ランタイムが必要です(パッケージ済みのNext.jsスタンドアロンサーバーは`deeptutor start`によって起動されます)。
```bash
mkdir -p my-deeptutor && cd my-deeptutor
pip install -U deeptutor
deeptutor init # ポート + LLMプロバイダー + オプション埋め込みを設定
deeptutor start # バックエンド + フロントエンドを起動; ターミナルを開いたまま
```
`deeptutor init`はバックエンドポート(デフォルト`8001`)、フロントエンドポート(デフォルト`3782`)、LLMプロバイダー / ベースURL / APIキー / モデル、およびKnowledge Base / RAG用のオプション埋め込みプロバイダーを設定します。
`deeptutor start`後、ターミナルに出力されたフロントエンドURLを開いてください(デフォルトは[http://127.0.0.1:3782](http://127.0.0.1:3782))。そのターミナルで`Ctrl+C`を押すとバックエンドとフロントエンドが両方停止します。手軽に試すために`deeptutor init`をスキップしても問題ありません。アプリはデフォルトのポートと空のモデル設定で起動し、後から**Settings → Models**で設定できます。
</details>
<details>
<summary><b>オプション2 — ソースからインストール</b> · チェックアウトに対して開発</summary>
チェックアウトに対して開発する場合。CIとDockerに合わせて**Python 3.11+**と**Node.js 22 LTS**を使用してください。
```bash
git clone https://github.com/HKUDS/DeepTutor.git
cd DeepTutor
# venvを作成(macOS/Linux)。Windows PowerShell:
# py -3.11 -m venv .venv ; .\.venv\Scripts\Activate.ps1
python3 -m venv .venv && source .venv/bin/activate
python -m pip install --upgrade pip
# バックエンド + フロントエンドの依存関係をインストール
python -m pip install -e .
( cd web && npm ci --legacy-peer-deps )
deeptutor init
deeptutor start
```
ソースインストールはローカルの`web/`ディレクトリに対してNext.jsをdevモードで実行します。その他(設定レイアウト、ポート、`Ctrl+C`での停止)はオプション1と同じです。
<details>
<summary><b>Conda環境</b><code>venv</code>の代わり)</summary>
```bash
conda create -n deeptutor python=3.11
conda activate deeptutor
python -m pip install --upgrade pip
```
</details>
<details>
<summary><b>オプションインストールエクストラ</b> — dev / partners / matrix / math-animator</summary>
```bash
pip install -e ".[dev]" # テスト/lintツール
pip install -e ".[partners]" # Partner IMチャンネルSDK + MCPクライアント
pip install -e ".[matrix]" # MatrixチャンネルE2EE/libolmなし
pip install -e ".[matrix-e2e]" # Matrix E2EE; libolmが必要
pip install -e ".[math-animator]" # Maninアドオン; LaTeX/ffmpeg/システムライブラリが必要
```
</details>
<details>
<summary><b>フロントエンド依存関係の調整とdevサーバーのトラブルシューティング</b></summary>
**フロントエンド依存関係の変更:** `npm install --legacy-peer-deps`を実行して`web/package-lock.json`を更新し、`web/package.json``web/package-lock.json`の両方をコミットしてください。
**devサーバーが動かない場合:** `deeptutor start`が応答しない既存のフロントエンドを報告する場合は、表示されたPIDを停止してください。実際にNext.jsプロセスが実行されていない場合、ロックファイルが古くなっています — それらを削除して再試行してください:
```bash
rm -f web/.next/dev/lock web/.next/lock
deeptutor start
```
</details>
</details>
<details>
<summary><b>オプション3 — Docker</b> · 自己完結型コンテナ1つ</summary>
フルWebアプリ用のコンテナ1つ。GitHub Container Registryのイメージ:
- `ghcr.io/hkuds/deeptutor:latest` — 安定版リリース
- `ghcr.io/hkuds/deeptutor:pre` — プレリリース(利用可能な場合)
> ポッドマン/rootless/読み取り専用rootfsデプロイメントと完全なインストール別ガイドについては [CONTAINERIZATION.md](../../CONTAINERIZATION.md) を参照してください。
```bash
docker run --rm --name deeptutor \
-p 127.0.0.1:3782:3782 \
-v deeptutor-data:/app/data \
ghcr.io/hkuds/deeptutor:latest
```
> **公開が必要なのは`3782`のみです。** ブラウザはフロントエンドオリジンのみと通信し、Next.jsミドルウェア(`web/proxy.ts`)が`/api/*`と`/ws/*`をコンテナ**内部の**FastAPIバックエンドに転送します。`8001`を公開(`-p 127.0.0.1:8001:8001`)するのはオプションで、curlやスクリプトでAPIに直接アクセスする場合にのみ便利です。
[http://127.0.0.1:3782](http://127.0.0.1:3782)を開いてください。コンテナは初回起動時に`/app/data/user/settings/*.json`を作成します。Web Settingsページからモデルプロバイダーを設定してください。設定、APIキー、ログ、ワークスペースファイル、メモリ、知識ベースは`deeptutor-data`ボリュームに永続化されます。
- **異なるホストポート:** 各`-p host:container`マッピングの左側を変更してください(例:`-p 127.0.0.1:8088:3782`)。`/app/data/user/settings/system.json`のコンテナ側ポートを変更する場合は、再起動して各マッピングの右側を一致するよう更新してください。
- **デタッチ:** `-d`を追加し、`docker logs -f deeptutor`でログを追跡、`docker stop deeptutor`で停止、名前を再利用する前に`docker rm deeptutor`を実行。`deeptutor-data`ボリュームは再起動をまたいで設定とワークスペースを保持します。
**リモートDocker / リバースプロキシ:** ブラウザはフロントエンドオリジン(`:3782`)のみと通信します。コンテナ内のNext.jsミドルウェアが`/api/*``/ws/*`をバックエンドサーバーサイドに転送します。一般的な単一コンテナの場合、APIベースをまったく設定しません — リバースプロキシ/TLS終端を`:3782`に向けるだけです。APIベースが必要なのは**分割デプロイメント**(バックエンドが別のコンテナ/ホスト)のみです:`data/user/settings/system.json``next_public_api_base`をフロントエンドサーバーがバックエンドに到達するためのネットワーク内アドレスに設定してください(サーバーサイドで読み取られ、ブラウザには送信されません)。
```json
{
"next_public_api_base": "http://backend:8001"
}
```
`next_public_api_base_external`(およびそのエイリアス`public_api_base`)は低優先度のフォールバックとして受け入れられます。CORSはAPIのURLではなくフロントエンドの**オリジン**を使用します。認証が無効の場合、DeepTutorはデフォルトで通常のHTTP/HTTPSブラウザオリジンを許可します。認証が有効の場合、正確なフロントエンドオリジンを追加してください:
```json
{
"cors_origins": ["https://deeptutor.example.com"]
}
```
<details>
<summary><b>ホスト上のOllama / LM Studio / llama.cpp / vLLM / Lemonadeへの接続</b></summary>
Docker内では、`localhost`はホストマシンではなくコンテナ自体です。ホスト上で実行中のモデルサービスに接続するには、ホストゲートウェイ(推奨)を使用してください:
```bash
docker run --rm --name deeptutor \
-p 127.0.0.1:3782:3782 -p 127.0.0.1:8001:8001 \
--add-host=host.docker.internal:host-gateway \
-v deeptutor-data:/app/data \
ghcr.io/hkuds/deeptutor:latest
```
**Settings → Models**でプロバイダーのBase URLを`host.docker.internal`に向けてください:
- Ollama LLM: `http://host.docker.internal:11434/v1`
- Ollama embedding: `http://host.docker.internal:11434/api/embed`
- LM Studio: `http://host.docker.internal:1234/v1`
- llama.cpp: `http://host.docker.internal:8080/v1`
- Lemonade: `http://host.docker.internal:13305/api/v1`
Docker DesktopmacOS/Windows)は通常`--add-host`なしで`host.docker.internal`を解決します。Linuxでは、このフラグが最新のDocker Engineでそのホスト名を作成するポータブルな方法です。
**Linuxの代替 — ホストネットワーキング:** `--network=host`を追加して`-p`フラグを削除します。コンテナはホストネットワークを直接共有するため、[http://127.0.0.1:3782](http://127.0.0.1:3782)(または`system.json``frontend_port`)を開き、ホストサービスには`http://127.0.0.1:11434/v1`のような通常のlocalhostのURLでアクセスできます。ホストネットワーキングはコンテナのポートをホスト上に直接公開し、既存のサービスと競合する可能性があります — それらをループバックに保つには`BACKEND_HOST=127.0.0.1``FRONTEND_HOST=127.0.0.1`を設定してください([CONTAINERIZATION.md](../../CONTAINERIZATION.md)参照)。
</details>
</details>
<details>
<summary><b>オプション4 — CLIのみ</b> · ソースチェックアウトからWeb UIなし</summary>
Web UIが不要な場合。CLIのみのパッケージはPyPIからではなく、ソースチェックアウトからインストールします。
```bash
git clone https://github.com/HKUDS/DeepTutor.git
cd DeepTutor
# venvを作成(macOS/Linux)。Windows PowerShell:
# py -3.11 -m venv .venv-cli ; .\.venv-cli\Scripts\Activate.ps1
python3 -m venv .venv-cli && source .venv-cli/bin/activate
python -m pip install --upgrade pip
python -m pip install -e ./packaging/deeptutor-cli
deeptutor init --cli
deeptutor chat
```
`deeptutor init --cli`はフルアプリと同じ`data/user/settings/`レイアウトを共有しますが、バックエンド/フロントエンドのポートプロンプトをスキップし、埋め込みをデフォルトで**オフ**にします(`deeptutor kb …`やRAGツールを使用する予定がある場合は`Yes`を選択してください)。完全なランタイムレイアウト(`system.json``auth.json``integrations.json``model_catalog.json``main.yaml``agents.yaml`)を書き込み、アクティブなLLMプロバイダーとモデルのプロンプトも表示します。
<details>
<summary><b>よく使うコマンド</b></summary>
```bash
deeptutor chat # インタラクティブREPL
deeptutor chat --capability deep_solve --tool rag --kb my-kb
deeptutor run chat "Explain Fourier transform"
deeptutor run deep_solve "Solve x^2 = 4" --tool rag --kb my-kb
deeptutor kb create my-kb --doc textbook.pdf
deeptutor memory show
deeptutor config show
```
</details>
ローカルの`deeptutor-cli`インストールにはWebアセットやサーバー依存関係がありません。ソースチェックアウトはそのままにしておいてください — 編集可能インストールはそれを参照します。後からWebアプリを追加するには、PyPIパッケージ(オプション1)をインストールして、同じワークスペースから`deeptutor init` + `deeptutor start`を実行してください。
</details>
<details>
<summary><b>コード実行サンドボックス(オフィススキル)</b> · docx / pdf / pptx / xlsx 用にモデル生成コードを実行</summary>
組み込みオフィススキル — **docx / pdf / pptx / xlsx** — は、モデルが短いPythonスクリプト(`python-docx``reportlab``openpyxl`など)を書き、`exec` / `code_execution`ツールで実行し、ダウンロードURLを返すことで機能します。これらのツールはサンドボックスバックエンドがアクティブなときにマウントされ、すべてのデプロイメント形態でデフォルトでアクティブです:
- **ローカル(オプション1/2)とDocker(オプション3、単一コンテナ):** 制限付きサブプロセスサンドボックスがモデルのコードを実行します(ローカルではホスト上、Dockerでは独自の隔離境界であるコンテナ内)。
- **docker-compose** `DEEPTUTOR_SANDBOX_RUNNER_URL`経由でハードニングされた最小権限の**ランナーサイドカー**(`Dockerfile.runner`)にルーティングされます — 最も強固な姿勢であり、利用可能な場合は自動的に優先されます。
サブプロセスサンドボックスは`data/user/settings/system.json``sandbox_allow_subprocess`設定で制御されます(デフォルト`true`)。ホスト上でモデル生成コードを実行することは実際の信頼上の決定です — ホスト側実行を無効にするには`false`に設定するか(または`DEEPTUTOR_SANDBOX_ALLOW_SUBPROCESS=0`をエクスポート)、オフィススキルがファイルを生成できなくなることに注意してください。
</details>
<details>
<summary><b>設定リファレンス</b> — <code>data/user/settings/</code>下の設定ファイル(JSON/YAML</summary>
`data/user/settings/`以下のものはすべてプレーンなJSON/YAMLです。ブラウザの**Settings**ページが推奨エディターです。
| ファイル | 目的 |
|:---|:---|
| `model_catalog.json` | LLM、埋め込み、検索プロバイダープロフィール;APIキー;アクティブモデル |
| `system.json` | バックエンド/フロントエンドポート、公開APIベース、CORS、SSL検証、添付ファイルディレクトリ |
| `auth.json` | オプション認証トグル、ユーザー名、パスワードハッシュ、トークン/クッキー設定 |
| `integrations.json` | オプションのPocketBaseとサイドカー統合設定 |
| `interface.json` | UIの言語/テーマ/サイドバー設定 |
| `main.yaml` | ランタイム動作のデフォルトとパス注入 |
| `agents.yaml` | 機能/ツールのtemperatureとトークン設定 |
プロジェクトルートの`.env`はアプリケーション設定ファイルとして**読み込まれません**。最小限のモデル設定では、**Settings → Models**を開き、LLMプロフィール(ベースURL / APIキー / モデル名)を追加して保存してください。Knowledge Base / RAG機能を使用する予定がある場合のみ埋め込みプロフィールを追加してください。
</details>
## 📖 DeepTutorを探索する
日常的に使用するメインサーフェスから始めましょう:Chat、Partners、My Agents、Co-Writer、Book、Knowledge Center、Learning Space、Memory、Settings。ツアーの最後はマルチユーザーデプロイメントとして共有・分離ワークスペースをカバーします。
<div align="center">
<img src="../../assets/figs/web-1.4.6+/OVERVIEW.png" alt="DeepTutorホーム — サイドバーにすべてのサーフェスを含むチャットワークスペース" width="900">
</div>
<details>
<summary><b>🏗️ システムアーキテクチャ</b></summary>
<div align="center">
<img src="../../assets/figs/system/system%20architecture.png" alt="DeepTutorシステムアーキテクチャ" width="900">
</div>
</details>
<details>
<summary><b>💬 Chat — 実際に使うエージェントループ</b></summary>
Chatはデフォルト機能であり、ほとんどの作業が始まる場所です。1つのスレッドで通常の会話、ツールの呼び出し、選択した知識ベースへのグラウンディング、添付ファイルの読み取り、画像生成、サブエージェントとの相談、ノートブックレコードの書き込みが可能で、ターンをまたいで同じコンテキストを維持します。
<div align="center">
<img src="../../assets/figs/web-1.4.6+/home/00-overview.png" alt="DeepTutorチャットワークスペース" width="900">
</div>
ループは意図的にシンプルです。モデルはラウンドで考え、役に立つときにツールを呼び出し、結果を観察し、ツールなしのメッセージで終了します。`ask_user`は特別で、推測する代わりに、エージェントはターンを一時停止し、構造化された明確化の質問をして、あなたが答えた後に再開できます。
<div align="center">
<img src="../../assets/figs/system/chat-agent-loop.png" alt="DeepTutorチャットエージェントループ" width="900">
</div>
ユーザーが切り替えられるツールは`brainstorm``web_search``paper_search``reason``geogebra_analysis` — 加えて、対応する生成モデルを設定すれば`imagegen``videogen`も利用できます。`rag``read_source``read_memory``write_memory``read_skill``load_tools``exec``web_fetch``ask_user``list_notebook``write_note``github``consult_subagent`などのコンテキスト依存ツールは、ターンに適切なコンテキストがある場合に自動的にマウントされます。
コンテキストには2種類あります:**スティッキーセッションコンテキスト**(サブエージェント、知識ベース、ペルソナ、モデル、音声)はコンポーザーツールバーに常駐し、ターンをまたいで持続します。**ワンタイム参照**(ファイル、チャット履歴、本、ノートブック、問題バンク、インポートしたエージェント)は単一のターンのために`+`メニューから追加します。
Chatはより深い機能へのローンチポイントでもあります:問題生成には**Quiz**、引用付きレポートには**Research**、チャート/図/アニメーションには**Visualize**、推論問題解決には**Solve**(「その他の機能」下)、学習計画フローには**Mastery Path**。
</details>
<details>
<summary><b>🤝 Partner — 同じブレインで動く永続コンパニオン</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/partners/00-partners%20overview.png" alt="DeepTutor Partnersワークスペース" width="900">
</div>
Partnersは独自のソウル、モデルポリシー、ライブラリ、メモリ、チャンネルを持つ永続コンパニオンです。別個のボットエンジンではありません。ウェブまたはIMからの受信メッセージは、パートナースコープのワークスペース内の通常の`ChatOrchestrator`ターンになります。Partnerは「個性を持ったチャットであり、電話番号を持っている」存在です。
<div align="center">
<img src="../../assets/figs/system/partners-architecture.png" alt="DeepTutor Partnersアーキテクチャ" width="900">
</div>
各Partnerには`SOUL.md`、モデル選択、チャンネル、ツールポリシー、割り当てられたライブラリがあります。知識ベース、スキル、ノートブックは`data/partners/<id>/workspace/`にコピーされるため、同じRAG、スキル、ノートブック、メモリツールが特別なケースなしに機能します。Partnerはオーナーのメモリを読み取れますが、自分自身のメモリにのみ書き込めます。
<div align="center">
<img src="../../assets/figs/web-1.4.6+/partners/02-IM%20config%20for%20each%20partner.png" alt="Partner ごとのIMチャンネル設定" width="900">
</div>
チャンネル層はスキーマ駆動で、インストール済みエクストラと設定された認証情報に応じて、Feishu、Telegram、Slack、Discord、DingTalk、QQ/NapCat、WeCom、WhatsApp、Zulip、Mattermost、Matrix、Mochat、Microsoft Teamsなどのプラットフォームに接続できます。PartnerはサブエージェントとしてMy Agentsに接続でき、通常のチャットターンから相談できます。詳細は以下の**My Agents**を参照してください。
</details>
<details>
<summary><b>🧑‍🚀 My Agents — 他のエージェントと相談・インポート</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/myagents/00-overview.png" alt="DeepTutor My Agentsワークスペース" width="900">
</div>
My Agentsは他のエージェントをDeepTutorのコンテキストにし、2つの異なることを行います。**ライブエージェントを接続** — マシン上のClaude CodeやCodex CLI、またはPartnerの1つ — してチャットターン内から相談できます。DeepTutorは実際に他のエージェントを*実行*し、`consult_subagent`ツールを介してその作業をActivityパネルにストリーミングします。Agentチップ(または`@`入力)で選択し、相談で取れるラウンド数を設定します。
<div align="center">
<img src="../../assets/figs/web-1.4.6+/home/08-subagent%20demo%20with%20claude%20code.png" alt="Claude Codeサブエージェントをライブで相談" width="900">
</div>
**過去の会話をインポート** — 既存のClaude CodeやCodexの履歴を名前付き、検索可能、再開可能なエージェントとして取り込みます。インポートする日を選択してください。更新すると再同期されます。チャットターンから`+` → My Agentsでインポートした会話を参照でき、DeepTutorはそれをサードパーティのトランスクリプトとして読み取ります — それはDeepTutor自身の声ではなく、*相手の*会話として保持されます。
</details>
<details>
<summary><b>✍️ Co-Writer — 選択対応Markdownドラフトツール</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/co-writer/00-overview.png" alt="DeepTutor Co-Writerワークスペース" width="900">
</div>
Co-Writerはレポート、チュートリアル、メモ、長文学習コンテンツのための分割表示Markdownワークスペースです。ドキュメントは自動保存され、ライブプレビュー(KaTeXの数式、図表フェンス)を表示し、下書きが再利用可能なコンテキストになったときにノートブックに保存できます。
<div align="center">
<img src="../../assets/figs/web-1.4.6+/co-writer/01-edit%20panel.png" alt="Co-Writerエディターとライブプレビュー" width="900">
</div>
その定義的なアイデアは**外科的編集**です。テキストの範囲を選択し、DeepTutorに書き直し、拡張、または短縮を依頼します。編集エージェントは知識ベースまたはウェブの証拠に基づいて変更をグラウンドし、ツール呼び出しのトレースを保持し、各変更を承認/拒否の差分として表示します — あなたが承認するまで何も適用されません。
</details>
<details>
<summary><b>📖 Book — 素材から生きている本を作成</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/book/00-book_overview.png" alt="DeepTutor Bookライブラリ" width="900">
</div>
Bookは選択したソースをインタラクティブな**生きている本**に変換します。静的なPDFではなく、タイプ指定されたブロックから構築された読書環境です。知識ベース、ノートブック、問題バンク、チャット履歴から本を開始できます。作成フローではコンテンツが生成される前に章のアウトラインを提案するため、盲目的な一発生成を受け入れるのではなく、構造を確認できます。
<p align="center">
<img src="../../assets/figs/web-1.4.6+/book/01-book-demo-quiz%20card.png" alt="Bookクイズブロック" width="31%">
&nbsp;
<img src="../../assets/figs/web-1.4.6+/book/02-book-demo-manim%20video.png" alt="Book Maninアニメーションブロック" width="31%">
&nbsp;
<img src="../../assets/figs/web-1.4.6+/book/03-book-demo%20interactive%20module.png" alt="Bookインタラクティブウィジェットブロック" width="31%">
</p>
各章はタイプ指定されたブロックにコンパイルされます — テキスト、コールアウト、クイズ、フラッシュカード、タイムライン、コード、図、インタラクティブHTML、アニメーション、概念グラフ、詳細解説、ユーザーノート — 各ページには独自のPage Chatがあります。ブロックは編集可能です:章全体を書き直すことなく、挿入、移動、再生成、またはブロックの種類を変更できます。`deeptutor book health``deeptutor book refresh-fingerprints`などのメンテナンスコマンドは、ソース知識がコンパイル済みページからドリフトした場合に検出するのに役立ちます。
</details>
<details>
<summary><b>📚 Knowledge Center — マルチエンジンRAGライブラリ</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/knowledge/00-overview.png" alt="DeepTutor Knowledge Center" width="900">
</div>
知識ベースはRAGの背後にあるドキュメントコレクションです — Chatターン、Co-Writerの編集、Book生成、Partnerの会話をグラウンドします。特徴的なのは**検索エンジンの選択**です:**LlamaIndex**(デフォルト、ローカルベクター + BM25)、**PageIndex**(ホスト型、ページレベル引用付き推論検索)、**GraphRAG**と**LightRAG**(知識グラフ検索)、**LightRAG Server**HTTP経由で接続する外部LightRAGインスタンスに検索をオフロード)、またはチューターがその場で読み書きするリンクされた**Obsidian**ボールト。各KBは1つのエンジンにバインドされます。
<div align="center">
<img src="../../assets/figs/web-1.4.6+/knowledge/01-create%20knowledge%20base.png" alt="知識ベースの作成" width="900">
</div>
KBを作成する際は、**新規作成**(ドキュメントをアップロードして新しいインデックスを構築)または**既存をリンク**(再インデックスなしで既に構築されたインデックスを再利用)を選択します。再インデックスは新しいフラットな`version-N`ディレクトリを書き込み、以前のものを保持するため、再構築中に作業中のインデックスが破壊されることはありません。解析に失敗したファイルを完全な削除・再構築なしで取り除けるよう、**error**状態のベースからでも単一のドキュメントを削除できます。ドキュメント解析(Text-only、MinerU、Docling、markitdown、PyMuPDF4LLM)は**Settings → Knowledge Base**で選択し、ローカルモデルのダウンロードはデフォルトでオフです。CLIは`deeptutor kb list``info``create``add``search``set-default``delete`でライフサイクルをミラーします。
</details>
<details>
<summary><b>🌐 Learning Space — スキル、ペルソナ、再利用可能なコンテキスト</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/learning-space/00-overview.png" alt="DeepTutor Learning Spaceハブ" width="900">
</div>
Learning Spaceはライブラリとパーソナライゼーション層です — 永続するものが置かれる場所です。**会話と素材**にはチャット履歴、ノートブック、問題バンク(各保存された質問にはあなたの回答、参照回答、説明が含まれます)が含まれます。**パーソナライゼーション**には習熟パス、ペルソナ(*peer*、*research-assistant*、*teacher*などの動作プリセット)、スキル(モデルがオンデマンドで読み取る`SKILL.md`プレイブック)が含まれます。ここのものはすべてChat、Partners、Co-Writer、Bookから再利用できます。
<div align="center">
<img src="../../assets/figs/web-1.4.6+/learning-space/07-%20download%20skills%20from%20eduhub.png" alt="EduHubからスキルをインポート" width="900">
</div>
すべてのスキルを自分で書く必要はありません。**EduHubからインポート**でコミュニティカタログを参照し、セキュリティゲートを通じてスキルをライブラリに直接ダウンロードできます([エコシステム](#-エコシステム--eduhubとスキルコミュニティ)参照)。
</details>
<details>
<summary><b>🧠 Memory — 検査可能なパーソナライゼーション</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/memory/00-overview.png" alt="DeepTutor Memoryの概要" width="900">
</div>
Memoryはファイルバックの3層システムで、読み取り、キュレーション、監査が可能です — 意図的に隠されたベクターストアではありません。**L1**はワークスペースミラーに加えた追記のみのイベントトレース(`trace/<surface>/<date>.jsonl`)、**L2**はサーフェスごとのキュレートされた事実(`L2/<surface>.md`)、**L3**はクロスサーフェス合成(`L3/<profile|recent|scope|preferences>.md`)です。L2はL1を引用し、L3はL2を引用するため、プロフィールの何も説明不能なものはありません。
<div align="center">
<img src="../../assets/figs/web-1.4.6+/memory/01-3%20layer%20memory%20graph.png" alt="DeepTutor Memoryグラフ" width="900">
</div>
Memory Graphはピラミッド全体を表示します — L3合成が中心、L2が中間リング、L1トレースが外側 — どんな合成された主張も背後にある正確な生のイベントまで追跡できます。Memoryは`chat``notebook``quiz``kb``book`、partner、`cowriter`サーフェスで追跡されます。コンソリデーターのUpdate / Audit / Dedupバジェットは**Settings → Memory**で調整します。
</details>
<details>
<summary><b>⚙️ Settings — ワンコントロールプレーン</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/settings/00-setting%20overview.png" alt="DeepTutor Settingsハブ" width="900">
</div>
Settingsはオペレーションコントロールプレーンで、ライブステータスストリップ(バックエンド、LLM、埋め込み、検索)とエリアごとのカードがあります:**外観**(テーマ + UI言語)、**ネットワーク**(APIベース、ポート、CORS)、**モデル**(LLM、埋め込み、検索、TTS、STT、画像生成、動画生成)、**Knowledge Base**(ドキュメント解析エンジン)、**Chat**(ツール、MCPサーバー、機能パラメーター)、**Partners & Agents**(ターンから相談できるサブエージェント)、**Memory**(コンソリデーターのバジェット)。
<div align="center">
<img src="../../assets/figs/web-1.4.6+/settings/01-appearance%20settings.png" alt="DeepTutor外観設定とテーマ" width="900">
</div>
ほとんどのセクションはドラフトと適用フローを使用するため、コミットする前にプロバイダーをテストできます。4つのテーマが箱に入っています:Default、Cream、Dark、Glass。プロジェクトルートの`.env`ファイルは意図的に無視されます。ランタイム設定は`DEEPTUTOR_HOME`または`deeptutor start --home`でアプリを別の場所に向けない限り、`data/user/settings/*.json`に保存されます。
</details>
<details>
<summary><b>👥 マルチユーザー — 共有デプロイメント</b> · オプション認証、分離されたユーザーワークスペース</summary>
認証はデフォルトで**オフ**です — DeepTutorはシングルユーザーで動作します。オンにすると、1つの`data/`ツリーで管理者ワークスペース、分離されたユーザーワークスペース、Partnerワークスペースが同居します:
```text
data/
├── user/ # 管理者ワークスペース + グローバル設定
├── users/<uid>/ # ユーザー単位スコープ:チャット履歴、メモリ、ノートブック、KB
├── partners/<id>/workspace/ # Partner(合成ユーザー)スコープ
└── system/ # auth/users.json · grants/<uid>.json · audit/usage.jsonl
```
**最初に登録したユーザーが管理者**になり、モデルカタログ、プロバイダー認証情報、共有知識ベース、スキル、ユーザー単位グラントを所有します。それ以外のユーザーは分離されたワークスペースと編集されたSettingsページを取得します — 管理者が割り当てたモデル、KB、スキルはスコープ付きの読み取り専用オプションとして表示され、生のAPIキーは見えません。
**有効化:** `data/user/settings/auth.json`で認証をオンにし、`deeptutor start`を再起動し、`/register`で最初の管理者を登録し、`/admin/users`からユーザーを追加し、グラントを通じてモデル、KB、スキル、Partner、ツール/MCPポリシー、コード実行アクセスを割り当てます。
> PocketBaseはシングルユーザー統合のままです — 外部ユーザーストアを組み込まない限り、マルチユーザーデプロイメントでは`integrations.pocketbase_url`を空白にしてください。
</details>
## ⌨️ DeepTutor CLI — エージェントネイティブインターフェース
1つの`deeptutor`バイナリで2つの使い方:ターミナルで生活する人のためのインタラクティブな**REPL**と、DeepTutorをツールとして動かす他のエージェントのための構造化された**JSON**。同じ機能、ツール、知識ベースがどちらでも利用できます。
<details>
<summary><b>自分で操作する</b></summary>
`deeptutor chat`でインタラクティブなREPLを開きます。`deeptutor run <capability> "<message>"`で1回のターンを実行して終了します。どちらも同じ`--capability``--tool``--kb``--config`フラグを使用します。
```bash
deeptutor chat # インタラクティブREPL
deeptutor chat --capability deep_solve --kb my-kb --tool rag
deeptutor run chat "Explain the Fourier transform" --tool rag --kb textbook
deeptutor run deep_research "Survey 2026 papers on RAG" \
--config mode=report --config depth=standard
```
Webアプリのすべてもここにあります — 知識ベース(`kb`)、セッション(`session`)、パートナー(`partner`)、スキル(`skill`)、ノートブック、メモリ、設定。全リストは以下を参照。
</details>
<details>
<summary><b>エージェントに操作させる</b></summary>
DeepTutorは*別のエージェントによって操作される*ように設計されています。任意の`run``--format json`を追加すると、各ターンが**NDJSON — 1行1イベント**`content``tool_call``tool_result``done`など)としてストリームされ、各行が`session_id`でタグ付けされます。実行はヘッドレスセーフです:TTYなしの`ask_user`一時停止は、ハングする代わりに空の応答で自動解決されます。
```bash
# 1回実行、マシン読み取り可能
deeptutor run deep_solve "Find d/dx[sin(x^2)]" --tool reason --format json
# 1つのステートフルセッションでターンを連鎖 — IDをキャプチャして再利用
SID=$(deeptutor run deep_research "Survey 2026 papers on RAG" \
--config mode=report --config depth=standard --format json \
| jq -r 'select(.type=="done").session_id')
deeptutor run deep_question "Quiz me on that survey" --session "$SID" --format json
```
リポジトリにはルートの[`SKILL.md`](../../SKILL.md)が含まれています — ツール使用可能なLLMにサーフェス全体を1回の読み取りで教える約150行のハンドオーバードキュメント。Claude Code、Codex、OpenCodeに渡してください(これらは`SKILL.md`を自動的に取得します)、または`deeptutor run`をLangChain / AutoGenループのツールとしてラップしてください。完全なレシピ:[Agent Handoff](https://deeptutor.info/docs/cli/agent-handoff/)。
</details>
<details>
<summary><b>コマンドリファレンス</b></summary>
| コマンド | 説明 |
|:---|:---|
| `deeptutor init` | 現在のワークスペースの`data/user/settings`を作成または更新 |
| `deeptutor start [--home PATH]` | バックエンド + フロントエンドを一緒に起動 |
| `deeptutor serve [--port PORT]` | FastAPIバックエンドのみ起動 |
| `deeptutor run <capability> <message>` | 単一機能ターンを実行(`chat``deep_solve``deep_question``deep_research``visualize``math_animator``mastery_path`);`--format json`でNDJSON出力 |
| `deeptutor chat` | 機能、ツール、KB、ノートブック、履歴コントロール付きインタラクティブREPL |
| `deeptutor partner list/create/start/stop` | IM接続Partnersを管理 |
| `deeptutor kb list/info/create/add/search/set-default/delete` | LlamaIndex知識ベースを管理 |
| `deeptutor skill search/install/list/remove/login/logout/publish/update` | スキルを管理、ハブからインストール、自分のスキルを公開(デフォルトは`eduhub:<slug>`、エコシステム参照) |
| `deeptutor memory show/clear` | L2/L3メモリドキュメントを検査またはL1/全メモリをクリア |
| `deeptutor session list/show/open/rename/delete` | 共有セッションを管理 |
| `deeptutor notebook list/create/show/add-md/replace-md/remove-record` | Markdownファイルからノートブックを管理 |
| `deeptutor book list/health/refresh-fingerprints` | 本を検査してソースフィンガープリントを更新 |
| `deeptutor plugin list/info` | 登録済みツールと機能を検査 |
| `deeptutor config show` | 設定サマリーを出力 |
| `deeptutor provider login <provider>` | プロバイダー認証(`openai-codex` OAuthログイン;`github-copilot`は既存のCopilot認証セッションを検証) |
</details>
<details>
<summary><b>CLIのみのディストリビューション</b></summary>
CLIのみのパッケージは`packaging/deeptutor-cli`にあります。このチェックアウトから、ソースからインストールしてください:
```bash
python -m pip install -e ./packaging/deeptutor-cli
```
まだPyPIには公開されていないため、メインの[はじめに](#-はじめに)セクションにはソースインストールのパスが記載されています。
</details>
## 🧩 エコシステム — EduHubとスキルコミュニティ
DeepTutorスキルはオープンな**Agent-Skills**フォーマットを使用します — `SKILL.md`プレイブック(YAMLフロントマター + Markdown)と任意の参照ファイルを含むフォルダです。これはDeepTutor固有のものではないため、このフォーマットを話すどんなレジストリもあなたのライブラリのソースになります。DeepTutorには**[EduHub](https://eduhub.deeptutor.info/)** — 独自の教育特化スキルレジストリ — がデフォルトハブとして組み込まれています。
<details>
<summary><b>EduHub — DeepTutorのスキルエコシステム</b></summary>
[**EduHub**](https://eduhub.deeptutor.info/)は、DeepTutorが教育指向のエージェントスキルを共有するために立ち上げたコミュニティハブです — ソクラテス式チューター、フラッシュカードビルダー、エッセイフィードバック、試験ブループリント、概念説明者など。DeepTutorに組み込まれているため、設定不要です:ベアスラッグまたは`eduhub:`プレフィックスでそこに解決されます。
**検索とインストール** — ブラウザで**Learning Space → スキル → EduHubからインポート**を開いてカタログを参照し、スキルをライブラリに直接ダウンロードできます。ターミナルから:
```bash
deeptutor skill search "socratic tutor" # EduHubを検索(デフォルトハブ)
deeptutor skill install socratic-tutor # 取得 → 検証 → 登録
deeptutor skill install eduhub:socratic-tutor@1.2.0 # ハブとバージョンを指定
deeptutor skill list # ハブの出所付きローカルスキル
```
**自分のスキルを公開**`SKILL.md`をパッケージ化してコミュニティに共有:
```bash
deeptutor skill login # EduHubへのブラウザサインイン
deeptutor skill publish ./my-skill # インタラクティブ:トラック + タグを選択してアップロード
deeptutor skill update # ロールバックまたは新バージョンをリリース
```
EduHubはまたスタンドアロンのClawHub互換レジストリでもあり、DeepTutor以外のエージェント(Claude Code、Codexなど)が`eduhub` CLI経由で直接使用できます — `npx eduhub install socratic-tutor`
</details>
<details>
<summary><b>インポートセキュリティゲート</b></summary>
ソースに関わらず、すべてのインポートはワークスペースに触れる前に**同じセキュリティゲート**を通過します:
- レジストリの**セキュリティ判定**が最初にチェックされます — フラグが立てられたパッケージは`--allow-unverified`を渡さない限り拒否されます;
- アーカイブはテキスト/スクリプト**サフィックスホワイトリスト**の後ろで防御的に展開されます(zip-slip / zip-bombガード)、バイナリはワークスペースに入れません;
- フロントマターはDeepTutorのスキーマに正規化され、`always:`が**削除**されるため、ダウンロードしたスキルはすべてのシステムプロンプトに自分自身を強制できません;
- 出所 — ハブ、バージョン、判定、インストール時間 — が監査と更新のために`.hub-lock.json`に記録されます。
マルチユーザーデプロイメントでは、インストールは管理者のみです:新しいスキルは管理者カタログに入り、グラントが割り当てるまで他のユーザーには見えません。管理者はロールアウトする前にそれを審査できます。
</details>
<details>
<summary><b>ClawHubとも互換性あり</b></summary>
DeepTutorはオープンなAgent-Skillsフォーマットに対応しているため、**[ClawHub](https://clawhub.ai/)**も一流のソースとして機能します — EduHubとともに組み込まれています。ハブプレフィックスで選択:
```bash
deeptutor skill search "git release notes" --hub clawhub
deeptutor skill install clawhub:git-release-notes@1.0.1
```
`settings/skill_hubs.json`にさらにレジストリを追加できます:`type: "clawhub"`エントリは互換性のあるHTTP APIを指し(EduHubとClawHubはどちらもそれを話します)、`type: "command"`はレジストリが配布するフェッチCLIをラップし、`"default"`はベアスラッグに使用するハブを選択します。すべて同じインポートゲートを通過します。
</details>
## 🌐 コミュニティ
### 📮 連絡先
DeepTutorは[Bingxi Zhao](https://github.com/pancacake)が[HKUDS](https://github.com/HKUDS)グループ内でリードするオープンソースプロジェクトで、**完全にオープンソースの形で**コミュニティと共に反復されています。現在、**いかなる有料オンライン製品も存在しません**。議論、アイデア、協力については**bingxizhao39@gmail.com**までお気軽にご連絡ください。
### 🙏 感謝
[**Chao Huang**](https://sites.google.com/view/chaoh)(HKUデータインテリジェンスラボディレクター)、HKUDSのラボメイト — 特に[**Jiahao Zhang**](https://github.com/zzhtx258)、[**Zirui Guo**](https://github.com/LarFii)、[**Xubin Ren**](https://github.com/Re-bin) — の温かいサポートに心から感謝します。また、毎日DeepTutorを形作ってくれる**オープンソースコミュニティ**にも深く感謝します:あなたたちのスター、Issue、プルリクエスト、ディスカッションがDeepTutorを形作っています。
DeepTutorは優れたオープンソースプロジェクトの肩の上に立っています。ツールとインスピレーションの両方を与えてくれた以下のプロジェクトに深く感謝します:
| プロジェクト | 役割 / インスピレーション |
|:---|:---|
| [**LlamaIndex**](https://github.com/run-llama/llama_index) | RAGパイプラインとドキュメントインデックスのバックボーン |
| [**nanobot**](https://github.com/HKUDS/nanobot) | オリジナルTutorBotを動かした超軽量エージェントエンジン *(HKUDS)* |
| [**LightRAG**](https://github.com/HKUDS/LightRAG) | シンプルで高速なRAG *(HKUDS)* |
| [**AutoAgent**](https://github.com/HKUDS/AutoAgent) | ゼロコードエージェントフレームワーク *(HKUDS)* |
| [**AI-Researcher**](https://github.com/HKUDS/AI-Researcher) | 自動化研究パイプライン *(HKUDS)* |
| [**OpenClaw**](https://github.com/openclaw/openclaw) | ClawHubの背後にあるオープンエージェントゲートウェイとスキルエコシステム |
| [**Codex**](https://github.com/openai/codex) | CLIワークフローにインスピレーションを与えたエージェントネイティブコーディングCLI |
| [**Claude Code**](https://github.com/anthropics/claude-code) | DeepTutorエージェントループにインスピレーションを与えたエージェントコーディングCLI |
| [**ManimCat**](https://github.com/Wing900/ManimCat) | Math AnimatorのためのAI駆動数学アニメーション生成 |
### 🗺️ ロードマップと貢献
DeepTutorが反復し改善し続け、最終的にオープンソースコミュニティへのギフトになることを望んでいます。[**ロードマップ**](https://github.com/HKUDS/DeepTutor/issues/498)は継続的に更新されています。アイテムに投票したり新しいものを提案したりできます。貢献したい方は、ブランチ戦略、コーディング基準、参加方法について[**貢献ガイド**](../../CONTRIBUTING.md)をご覧ください。
<div align="center">
DeepTutorがコミュニティへのギフトになることを願っています。 🎁
<a href="https://github.com/HKUDS/DeepTutor/graphs/contributors">
<img src="https://contrib.rocks/image?repo=HKUDS/DeepTutor&max=999" alt="Contributors" />
</a>
</div>
<div align="center">
<a href="https://www.star-history.com/#HKUDS/DeepTutor&type=timeline&legend=top-left">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=HKUDS/DeepTutor&type=timeline&theme=dark&legend=top-left" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=HKUDS/DeepTutor&type=timeline&legend=top-left" />
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=HKUDS/DeepTutor&type=timeline&legend=top-left" />
</picture>
</a>
</div>
<p align="center">
<a href="https://www.star-history.com/hkuds/deeptutor">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/badge?repo=HKUDS/DeepTutor&theme=dark" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/badge?repo=HKUDS/DeepTutor" />
<img alt="Star History Rank" src="https://api.star-history.com/badge?repo=HKUDS/DeepTutor" />
</picture>
</a>
</p>
<div align="center">
[Apache License 2.0](../../LICENSE)に基づきライセンス。
<p>
<img src="https://visitor-badge.laobi.icu/badge?page_id=HKUDS.DeepTutor&style=for-the-badge&color=00d4ff" alt="Views">
</p>
</div>
+707
View File
@@ -0,0 +1,707 @@
<div align="center">
<p align="center"><img src="../../assets/figs/logo/logo.png" alt="DeepTutor logo" height="56" style="vertical-align: middle;">&nbsp;<img src="../../assets/figs/logo/banner.png" alt="DeepTutor" height="48" style="vertical-align: middle;"></p>
# DeepTutor: Dożywotnie Spersonalizowane Korepetycje
<p align="center">
<a href="https://deeptutor.info" target="_blank"><img alt="Docs — deeptutor.info" src="https://img.shields.io/badge/Docs-deeptutor.info%20%E2%86%97-0A0A0A?style=for-the-badge&labelColor=F5F5F4" height="36"></a>
</p>
<p align="center">
<a href="https://trendshift.io/repositories/17099?utm_source=repository-badge&amp;utm_medium=badge&amp;utm_campaign=badge-repository-17099" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/repositories/17099" alt="HKUDS%2FDeepTutor | Trendshift" width="250" height="55"/></a>&nbsp;
<a href="https://trendshift.io/repositories/17099?utm_source=trendshift-badge&amp;utm_medium=badge&amp;utm_campaign=badge-trendshift-17099" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/17099/daily" alt="HKUDS%2FDeepTutor | Trendshift" width="250" height="55"/></a>&nbsp;
<a href="https://trendshift.io/repositories/17099?utm_source=trendshift-badge&amp;utm_medium=badge&amp;utm_campaign=badge-trendshift-17099" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/17099/weekly?language=Python" alt="HKUDS%2FDeepTutor | Trendshift" width="250" height="55"/></a>
</p>
<p align="center">
<a href="../../README.md"><img alt="English" height="40" src="https://img.shields.io/badge/English-CDCFD4"></a>&nbsp;
<a href="README_CN.md"><img alt="简体中文" height="40" src="https://img.shields.io/badge/简体中文-CDCFD4"></a>&nbsp;
<a href="README_JA.md"><img alt="日本語" height="40" src="https://img.shields.io/badge/日本語-CDCFD4"></a>&nbsp;
<a href="README_ES.md"><img alt="Español" height="40" src="https://img.shields.io/badge/Español-CDCFD4"></a>&nbsp;
<a href="README_FR.md"><img alt="Français" height="40" src="https://img.shields.io/badge/Français-CDCFD4"></a>&nbsp;
<a href="README_AR.md"><img alt="Arabic" height="40" src="https://img.shields.io/badge/Arabic-CDCFD4"></a>&nbsp;
<a href="README_RU.md"><img alt="Русский" height="40" src="https://img.shields.io/badge/Русский-CDCFD4"></a>&nbsp;
<a href="README_HI.md"><img alt="Hindi" height="40" src="https://img.shields.io/badge/Hindi-CDCFD4"></a>&nbsp;
<a href="README_PT.md"><img alt="Português" height="40" src="https://img.shields.io/badge/Português-CDCFD4"></a>&nbsp;
<a href="README_TH.md"><img alt="Thai" height="40" src="https://img.shields.io/badge/Thai-CDCFD4"></a>&nbsp;
<a href="README_PL.md"><img alt="Polski" height="40" src="https://img.shields.io/badge/Polski-BCDCF7"></a>
</p>
[![Python 3.11+](https://img.shields.io/badge/Python-3.11%2B-3776AB?style=flat-square&logo=python&logoColor=white)](https://www.python.org/downloads/)
[![Next.js 16](https://img.shields.io/badge/Next.js-16-000000?style=flat-square&logo=next.js&logoColor=white)](https://nextjs.org/)
[![License](https://img.shields.io/badge/License-Apache_2.0-blue?style=flat-square)](../../LICENSE)
[![GitHub release](https://img.shields.io/github/v/release/HKUDS/DeepTutor?style=flat-square&color=brightgreen)](https://github.com/HKUDS/DeepTutor/releases)
[![arXiv](https://img.shields.io/badge/arXiv-2604.26962-b31b1b?style=flat-square&logo=arxiv&logoColor=white)](https://arxiv.org/abs/2604.26962)
[![Discord](https://img.shields.io/badge/Discord-Community-5865F2?style=flat-square&logo=discord&logoColor=white)](https://discord.gg/eRsjPgMU4t)
[![Feishu](https://img.shields.io/badge/Feishu-Group-00D4AA?style=flat-square&logo=feishu&logoColor=white)](../../Communication.md)
[![WeChat](https://img.shields.io/badge/WeChat-Group-07C160?style=flat-square&logo=wechat&logoColor=white)](https://github.com/HKUDS/DeepTutor/issues/78)
[Funkcje](#-główne-funkcje) · [Zacznij](#-pierwsze-kroki) · [Eksploruj](#-eksploracja-deeptutor) · [CLI](#-deeptutor-cli--interfejs-natywny-dla-agentów) · [Ekosystem](#-ekosystem--eduhub-i-społeczność-umiejętności) · [Społeczność](#-społeczność)
</div>
---
> 🤝 **Zapraszamy do wszelkich form współpracy!** Głosuj na elementy planu działania lub proponuj nowe w [`Roadmap`](https://github.com/HKUDS/DeepTutor/issues/498), a szczegóły dotyczące strategii gałęzi, standardów kodowania i sposobu rozpoczęcia pracy znajdziesz w naszym [Przewodniku dla współtwórców](../../CONTRIBUTING.md).
### 📰 Aktualności
- **2026-05-22** 🌐 Oficjalna strona dokumentacji dostępna na [**deeptutor.info**](https://deeptutor.info/) — przewodniki, odniesienia i wycieczki po możliwościach w jednym miejscu.
- **2026-04-19** 🎉 20 tys. gwiazdek w 111 dni! Dziękujemy za wsparcie na drodze do prawdziwie spersonalizowanych, inteligentnych korepetycji.
- **2026-04-10** 📄 Nasz artykuł jest już dostępny na arXiv — przeczytaj [preprint](https://arxiv.org/abs/2604.26962), aby dowiedzieć się więcej o projekcie i pomysłach stojących za DeepTutor.
- **2026-02-06** 🚀 10 tys. gwiazdek w zaledwie 39 dni! Ogromne podziękowania dla naszej niesamowitej społeczności.
- **2026-01-01** 🎊 Szczęśliwego Nowego Roku! Dołącz do naszego [Discorda](https://discord.gg/eRsjPgMU4t), [WeChat](https://github.com/HKUDS/DeepTutor/issues/78) lub [Dyskusji](https://github.com/HKUDS/DeepTutor/discussions) — razem kształtujmy przyszłość DeepTutor.
- **2025-12-29** 🎓 DeepTutor jest oficjalnie wydany!
## ✨ Główne funkcje
DeepTutor to natywne dla agentów środowisko nauki, które łączy korepetycje, rozwiązywanie problemów, generowanie quizów, badania, wizualizacje i ćwiczenia opanowania wiedzy w jednym rozszerzalnym systemie.
- **Jedno środowisko dla wszystkich trybów** — Chat, Quiz, Research, Visualize, Solve i Mastery Path działają na tej samej pętli agenta, więc zmieniasz cel, a nie silnik, a kontekst podąża za uczącym się.
- **Połączony kontekst uczenia się** — bazy wiedzy, książki, szkice Co-Writer, notatniki, banki pytań, persony i Memory są dostępne we wszystkich przepływach pracy zamiast żyć w izolowanych narzędziach.
- **Subagenty i Partners** — konsultuj działającego Claude Code, Codex lub Partner z dowolnej tury (lub importuj ich poprzednie konwersacje) i uruchamiaj stałych towarzyszy IM na tym samym mózgu.
- **Wielosilnikowa wiedza** — wersjonowane biblioteki RAG z LlamaIndex, PageIndex, GraphRAG, LightRAG lub podłączonym vault Obsidian, z podłączalnym parsowaniem dokumentów.
- **Rozszerzalne narzędzia i umiejętności** — wbudowane narzędzia, serwery MCP, modele generowania obrazów / wideo / głosu oraz instalowalne umiejętności społecznościowe z EduHub.
- **Inspektowalna pamięć** — ślady L1, podsumowania powierzchni L2 i synteza L3 sprawiają, że personalizacja jest widoczna i edytowalna, a Memory Graph śledzi każde twierdzenie z powrotem do jego dowodów.
---
## 🚀 Pierwsze kroki
DeepTutor oferuje cztery ścieżki instalacji. Wszystkie współdzielą jeden układ obszaru roboczego: ustawienia żyją w `data/user/settings/` pod katalogiem, z którego uruchamiasz (lub pod `DEEPTUTOR_HOME` / `deeptutor start --home` jeśli ustawisz je jawnie). Dla pełnej aplikacji zalecany przepływ to **wybierz katalog obszaru roboczego → zainstaluj → `deeptutor init` → `deeptutor start`**.
<details>
<summary><b>Opcja 1 — Instalacja z PyPI</b> · pełna lokalna aplikacja Web + CLI, bez potrzeby klonowania</summary>
Pełna lokalna aplikacja Web + CLI, bez potrzeby klonowania. Wymaga **Python 3.11+** i środowiska uruchomieniowego **Node.js 20+** na PATH (spakowany serwer standalone Next.js jest uruchamiany przez `deeptutor start`).
```bash
mkdir -p my-deeptutor && cd my-deeptutor
pip install -U deeptutor
deeptutor init # pyta o porty + dostawcę LLM + opcjonalne osadzanie
deeptutor start # uruchamia backend + frontend; utrzymuj terminal otwarty
```
`deeptutor init` pyta o port backendu (domyślnie `8001`), port frontendu (domyślnie `3782`), dostawcę LLM / bazowy URL / klucz API / model i opcjonalnego dostawcę osadzania dla Bazy wiedzy / RAG.
Po `deeptutor start` otwórz adres URL frontendu wydrukowany w terminalu — domyślnie [http://127.0.0.1:3782](http://127.0.0.1:3782). Naciśnij `Ctrl+C` w tym terminalu, aby zatrzymać backend i frontend. Pominięcie `deeptutor init` jest dobre dla szybkiego testu; aplikacja uruchamia się z domyślnymi portami i pustymi ustawieniami modelu, skonfiguruj je później w **Settings → Models**.
</details>
<details>
<summary><b>Opcja 2 — Instalacja ze źródeł</b> · programowanie przy użyciu kodu źródłowego</summary>
Do programowania przy użyciu kodu źródłowego. Użyj **Python 3.11+** i **Node.js 22 LTS**, aby dopasować do CI i Dockera.
```bash
git clone https://github.com/HKUDS/DeepTutor.git
cd DeepTutor
# Utwórz venv (macOS/Linux). Windows PowerShell:
# py -3.11 -m venv .venv ; .\.venv\Scripts\Activate.ps1
python3 -m venv .venv && source .venv/bin/activate
python -m pip install --upgrade pip
# Zainstaluj zależności backendu + frontendu
python -m pip install -e .
( cd web && npm ci --legacy-peer-deps )
deeptutor init
deeptutor start
```
Instalacje ze źródeł uruchamiają Next.js w trybie deweloperskim względem lokalnego katalogu `web/`; wszystko inne (układ konfiguracji, porty, zatrzymanie za pomocą `Ctrl+C`) odpowiada Opcji 1.
<details>
<summary><b>Środowisko Conda</b> (zamiast <code>venv</code>)</summary>
```bash
conda create -n deeptutor python=3.11
conda activate deeptutor
python -m pip install --upgrade pip
```
</details>
<details>
<summary><b>Opcjonalne dodatki instalacyjne</b> — dev / partners / matrix / math-animator</summary>
```bash
pip install -e ".[dev]" # narzędzia testów/lint
pip install -e ".[partners]" # SDK kanałów IM Partners + klient MCP
pip install -e ".[matrix]" # kanał Matrix bez E2EE/libolm
pip install -e ".[matrix-e2e]" # Matrix E2EE; wymaga libolm
pip install -e ".[math-animator]" # addon Manim; wymaga LaTeX/ffmpeg/bibliotek systemowych
```
</details>
<details>
<summary><b>Dostosowania zależności frontendowych i rozwiązywanie problemów z serwerem deweloperskim</b></summary>
**Zmiana zależności frontendowych:** uruchom `npm install --legacy-peer-deps`, aby odświeżyć `web/package-lock.json`, a następnie zatwierdź zarówno `web/package.json`, jak i `web/package-lock.json`.
**Zablokowany serwer deweloperski:** jeśli `deeptutor start` zgłasza istniejący frontend, który nie odpowiada, zatrzymaj PID, który wydrukuje. Jeśli żaden proces Next.js nie jest uruchomiony, pliki blokady są przestarzałe — usuń je i spróbuj ponownie:
```bash
rm -f web/.next/dev/lock web/.next/lock
deeptutor start
```
</details>
</details>
<details>
<summary><b>Opcja 3 — Docker</b> · jeden samodzielny kontener</summary>
Jeden kontener dla pełnej aplikacji Web. Obrazy w GitHub Container Registry:
- `ghcr.io/hkuds/deeptutor:latest` — stabilne wydanie
- `ghcr.io/hkuds/deeptutor:pre` — wersja wstępna, gdy dostępna
> Zobacz [CONTAINERIZATION.md](../../CONTAINERIZATION.md) w celu uzyskania informacji o wdrożeniach podman/rootless/read-only-rootfs i pełnym przewodniku per-instalacja.
```bash
docker run --rm --name deeptutor \
-p 127.0.0.1:3782:3782 \
-v deeptutor-data:/app/data \
ghcr.io/hkuds/deeptutor:latest
```
> **Tylko `3782` musi być opublikowane.** Przeglądarka komunikuje się wyłącznie z serwerem frontendu; middleware Next.js (`web/proxy.ts`) przekazuje `/api/*` i `/ws/*` do backendu FastAPI **wewnątrz kontenera**. Opublikowanie `8001` (`-p 127.0.0.1:8001:8001`) jest opcjonalne — przydatne tylko do bezpośredniego uderzania w API z curl lub skryptów.
Otwórz [http://127.0.0.1:3782](http://127.0.0.1:3782). Kontener tworzy `/app/data/user/settings/*.json` przy pierwszym uruchomieniu; skonfiguruj dostawców modeli ze strony Web Settings. Konfiguracja, klucze API, dzienniki, pliki obszaru roboczego, pamięć i bazy wiedzy są przechowywane w woluminie `deeptutor-data`.
- **Różne porty hosta:** zmień lewą stronę każdego mapowania `-p host:kontener` (np. `-p 127.0.0.1:8088:3782`). Jeśli zmienisz porty po stronie kontenera w `/app/data/user/settings/system.json`, uruchom ponownie i zaktualizuj prawą stronę każdego mapowania, aby pasowała.
- **Odłączony:** dodaj `-d`, następnie `docker logs -f deeptutor`, aby śledzić, `docker stop deeptutor`, aby zatrzymać, `docker rm deeptutor` przed ponownym użyciem nazwy. Wolumin `deeptutor-data` przechowuje ustawienia i obszar roboczy między restartami.
**Zdalny Docker / odwrotne proxy:** przeglądarka komunikuje się wyłącznie z serwerem frontendu (`:3782`); middleware Next.js wewnątrz kontenera przekazuje `/api/*` i `/ws/*` do serwera backendu po stronie serwera. W typowym przypadku jednego kontenera nie konfigurujesz w ogóle bazowego adresu API — po prostu skieruj swój reverse proxy / terminator TLS na `:3782`. Bazowy adres API jest potrzebny tylko dla **wdrożenia rozdzielonego** (backend w osobnym kontenerze/hoście): ustaw `next_public_api_base` w `data/user/settings/system.json` na adres sieciowy, którego serwer frontendu używa do osiągnięcia backendu (jest czytany po stronie serwera, nigdy nie wysyłany do przeglądarki).
```json
{
"next_public_api_base": "http://backend:8001"
}
```
`next_public_api_base_external` (i jego alias `public_api_base`) są akceptowane jako fallbacki o niższym priorytecie. CORS używa **źródeł** frontendu, a nie adresów URL API. Przy wyłączonym uwierzytelnianiu DeepTutor domyślnie zezwala na normalne źródła przeglądarki HTTP/HTTPS. Przy włączonym uwierzytelnianiu dodaj dokładne źródła frontendu:
```json
{
"cors_origins": ["https://deeptutor.example.com"]
}
```
<details>
<summary><b>Łączenie z Ollama / LM Studio / llama.cpp / vLLM / Lemonade na hoście</b></summary>
Wewnątrz Dockera `localhost` to sam kontener, a nie maszyna hosta. Aby dotrzeć do usługi modelu działającej na hoście, użyj bramy hosta (zalecane):
```bash
docker run --rm --name deeptutor \
-p 127.0.0.1:3782:3782 -p 127.0.0.1:8001:8001 \
--add-host=host.docker.internal:host-gateway \
-v deeptutor-data:/app/data \
ghcr.io/hkuds/deeptutor:latest
```
Następnie w **Settings → Models** wskaż bazowy URL dostawcy na `host.docker.internal`:
- Ollama LLM: `http://host.docker.internal:11434/v1`
- Ollama embedding: `http://host.docker.internal:11434/api/embed`
- LM Studio: `http://host.docker.internal:1234/v1`
- llama.cpp: `http://host.docker.internal:8080/v1`
- Lemonade: `http://host.docker.internal:13305/api/v1`
Docker Desktop (macOS/Windows) zazwyczaj rozwiązuje `host.docker.internal` bez `--add-host`. Na Linuksie flaga jest przenośnym sposobem tworzenia tej nazwy hosta w nowoczesnym Docker Engine.
**Alternatywa dla Linuksa — sieć hosta:** dodaj `--network=host` i usuń flagi `-p`. Kontener bezpośrednio współdzieli sieć hosta, więc otwórz [http://127.0.0.1:3782](http://127.0.0.1:3782) (lub `frontend_port` w `system.json`), a usługi hosta są dostępne pod normalnymi adresami URL localhost jak `http://127.0.0.1:11434/v1`. Pamiętaj, że sieciowanie hosta bezpośrednio ujawnia porty kontenera na hoście i może powodować konflikty z istniejącymi usługami — aby utrzymać je na loopback, ustaw `BACKEND_HOST=127.0.0.1` i `FRONTEND_HOST=127.0.0.1` (patrz [CONTAINERIZATION.md](../../CONTAINERIZATION.md)).
</details>
</details>
<details>
<summary><b>Opcja 4 — Tylko CLI</b> · bez interfejsu webowego, z kodu źródłowego</summary>
Gdy nie potrzebujesz interfejsu webowego. Pakiet tylko CLI jest instalowany ze źródłowego kodu, a nie z PyPI.
```bash
git clone https://github.com/HKUDS/DeepTutor.git
cd DeepTutor
# Utwórz venv (macOS/Linux). Windows PowerShell:
# py -3.11 -m venv .venv-cli ; .\.venv-cli\Scripts\Activate.ps1
python3 -m venv .venv-cli && source .venv-cli/bin/activate
python -m pip install --upgrade pip
python -m pip install -e ./packaging/deeptutor-cli
deeptutor init --cli
deeptutor chat
```
`deeptutor init --cli` współdzieli ten sam układ `data/user/settings/` co pełna aplikacja, ale pomija monity o porty backendu/frontendu i domyślnie wyłącza osadzanie (wybierz `Yes` jeśli planujesz używać `deeptutor kb …` lub narzędzi RAG). Nadal zapisuje kompletny układ środowiska uruchomieniowego (`system.json`, `auth.json`, `integrations.json`, `model_catalog.json`, `main.yaml`, `agents.yaml`) i nadal pyta o aktywnego dostawcę LLM i model.
<details>
<summary><b>Typowe polecenia</b></summary>
```bash
deeptutor chat # interaktywny REPL
deeptutor chat --capability deep_solve --tool rag --kb my-kb
deeptutor run chat "Explain Fourier transform"
deeptutor run deep_solve "Solve x^2 = 4" --tool rag --kb my-kb
deeptutor kb create my-kb --doc textbook.pdf
deeptutor memory show
deeptutor config show
```
</details>
Lokalna instalacja `deeptutor-cli` nie zawiera zasobów webowych ani zależności serwera. Zachowaj kod źródłowy — instalacja edytowalna wskazuje na niego. Aby dodać aplikację Web później, zainstaluj pakiet PyPI (Opcja 1) i uruchom `deeptutor init` + `deeptutor start` z tego samego obszaru roboczego.
</details>
<details>
<summary><b>Piaskownica wykonania kodu (umiejętności biurowe)</b> · uruchamianie kodu generowanego przez model dla docx / pdf / pptx / xlsx</summary>
Wbudowane umiejętności biurowe — **docx / pdf / pptx / xlsx** — działają, sprawiając że model pisze krótki skrypt Python (`python-docx`, `reportlab`, `openpyxl`, …), uruchamia go przez narzędzia `exec` / `code_execution` i zwraca adres URL do pobrania. Te narzędzia montują się za każdym razem, gdy backend piaskownicy jest aktywny, co ma miejsce **domyślnie** w każdym kształcie wdrożenia:
- **Lokalne (Opcja 1 / 2) i Docker (Opcja 3, pojedynczy kontener):** ograniczona piaskownica podprocesu uruchamia kod modelu (lokalnie na hoście lub wewnątrz kontenera pod Dockerem — kontener będący własną granicą izolacji).
- **docker-compose:** zamiast tego kierowany do utwardzonego, o najmniejszych uprawnieniach **sidecar runner** (`Dockerfile.runner`) przez `DEEPTUTOR_SANDBOX_RUNNER_URL` — najsilniejsza postawa, automatycznie preferowana gdy jest obecna.
Piaskownica podprocesu jest kontrolowana przez ustawienie `sandbox_allow_subprocess` w `data/user/settings/system.json` (domyślnie `true`). Uruchamianie kodu generowanego przez model na twoim hoście to prawdziwa decyzja dotycząca zaufania — ustaw na `false` (lub eksportuj `DEEPTUTOR_SANDBOX_ALLOW_SUBPROCESS=0`), aby wyłączyć wykonanie po stronie hosta kosztem tego, że umiejętności biurowe nie będą mogły produkować plików.
</details>
<details>
<summary><b>Odniesienie do konfiguracji</b> — pliki konfiguracyjne w <code>data/user/settings/</code> (JSON/YAML)</summary>
Wszystko w `data/user/settings/` to zwykły JSON/YAML. Strona **Settings** w przeglądarce jest zalecanym edytorem.
| Plik | Cel |
|:---|:---|
| `model_catalog.json` | Profile dostawców LLM, osadzania i wyszukiwania; klucze API; aktywne modele |
| `system.json` | Porty backendu/frontendu, publiczna baza API, CORS, weryfikacja SSL, katalog załączników |
| `auth.json` | Opcjonalny przełącznik uwierzytelniania, nazwa użytkownika, hash hasła, ustawienia tokena/cookie |
| `integrations.json` | Opcjonalne ustawienia PocketBase i integracji sidecar |
| `interface.json` | Preferencje języka / motywu / paska bocznego interfejsu użytkownika |
| `main.yaml` | Domyślne zachowanie środowiska uruchomieniowego i wstrzykiwanie ścieżek |
| `agents.yaml` | Ustawienia temperatury i tokenów możliwości/narzędzi |
Plik `.env` w katalogu głównym projektu **nie** jest czytany jako plik konfiguracyjny aplikacji. Dla minimalnej konfiguracji modelu otwórz **Settings → Models**, dodaj profil LLM (bazowy URL / klucz API / nazwa modelu) i zapisz. Dodaj profil osadzania tylko jeśli planujesz korzystać z funkcji Bazy wiedzy / RAG.
</details>
## 📖 Eksploracja DeepTutor
Zacznij od głównych powierzchni, których będziesz używać na co dzień: Chat, Partners, My Agents, Co-Writer, Book, Knowledge Center, Learning Space, Memory i Settings. Wycieczka obejmuje następnie wdrożenia dla wielu użytkowników dla współdzielonych, izolowanych obszarów roboczych.
<div align="center">
<img src="../../assets/figs/web-1.4.6+/OVERVIEW.png" alt="Strona główna DeepTutor — obszar roboczy Chat z każdą powierzchnią w pasku bocznym" width="900">
</div>
<details>
<summary><b>🏗️ Architektura systemu</b></summary>
<div align="center">
<img src="../../assets/figs/system/system%20architecture.png" alt="Architektura systemu DeepTutor" width="900">
</div>
</details>
<details>
<summary><b>💬 Chat — Pętla agenta, z której naprawdę korzystasz</b></summary>
Chat to domyślna możliwość i miejsce, gdzie zaczyna się większość pracy. Jeden wątek może rozmawiać normalnie, wywoływać narzędzia, opierać się na wybranych bazach wiedzy, czytać załączniki, generować obrazy, konsultować subagentów, pisać rekordy notatnika i kontynuować z tym samym kontekstem przez tury.
<div align="center">
<img src="../../assets/figs/web-1.4.6+/home/00-overview.png" alt="Obszar roboczy czatu DeepTutor" width="900">
</div>
Pętla jest celowo prosta: model myśli w rundach, wywołuje narzędzia gdy są przydatne, obserwuje wyniki i kończy wiadomością bez narzędzi. `ask_user` jest wyjątkowy — zamiast zgadywać, agent może wstrzymać turę, zadać ustrukturyzowane pytanie wyjaśniające i wznowić po odpowiedzi.
<div align="center">
<img src="../../assets/figs/system/chat-agent-loop.png" alt="Pętla agenta czatu DeepTutor" width="900">
</div>
Narzędzia przełączalne przez użytkownika to `brainstorm`, `web_search`, `paper_search`, `reason` i `geogebra_analysis` — plus `imagegen` i `videogen` po skonfigurowaniu odpowiedniego modelu generowania. Narzędzia kontekstowe takie jak `rag`, `read_source`, `read_memory`, `write_memory`, `read_skill`, `load_tools`, `exec`, `web_fetch`, `ask_user`, `list_notebook`, `write_note`, `github` i `consult_subagent` montują się automatycznie gdy tura ma odpowiedni kontekst.
Kontekst dzieli się na dwa rodzaje: **trwały kontekst sesji** (subagent, bazy wiedzy, persona, model, głos) żyje na pasku narzędziowym kompozytora i jest zachowany przez tury; **jednorazowe odwołania** (pliki, historia czatu, książki, notatniki, bank pytań, zaimportowani agenci) pochodzą z menu `+` dla jednej tury.
Chat jest również punktem startowym dla głębszych możliwości: **Quiz** do generowania pytań, **Research** do cytowanych raportów, **Visualize** do wykresów / diagramów / animacji i — w sekcji *More Capabilities***Solve** do wypracowanego rozumowania i **Mastery Path** do przepływów planu nauki.
</details>
<details>
<summary><b>🤝 Partner — Stali towarzysze na tym samym mózgu</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/partners/00-partners%20overview.png" alt="Obszar roboczy Partners DeepTutor" width="900">
</div>
Partners to stali towarzysze z własną duszą, polityką modelu, biblioteką, pamięcią i kanałami. Nie są osobnym silnikiem bota: każda przychodząca wiadomość webowa lub IM staje się normalną turą `ChatOrchestrator` wewnątrz obszaru roboczego z zakresem partnera. Partner to „czat który ma osobowość i numer telefonu."
<div align="center">
<img src="../../assets/figs/system/partners-architecture.png" alt="Architektura Partners DeepTutor" width="900">
</div>
Każdy partner ma `SOUL.md`, wybór modelu, kanały, politykę narzędzi i przypisaną bibliotekę. Bazy wiedzy, umiejętności i notatniki są kopiowane do `data/partners/<id>/workspace/`, więc te same narzędzia RAG, umiejętności, notatnika i pamięci działają bez specjalnych przypadków. Partner czyta pamięć swojego właściciela, ale zapisuje tylko do własnej.
<div align="center">
<img src="../../assets/figs/web-1.4.6+/partners/02-IM%20config%20for%20each%20partner.png" alt="Konfiguracja kanału IM per partner" width="900">
</div>
Warstwa kanałów jest sterowana schematem i może łączyć się z platformami IM takimi jak Feishu, Telegram, Slack, Discord, DingTalk, QQ/NapCat, WeCom, WhatsApp, Zulip, Mattermost, Matrix, Mochat i Microsoft Teams w zależności od zainstalowanych dodatków i skonfigurowanych danych uwierzytelniających. Partner może być również podłączony jako subagent i konsultowany z normalnej tury czatu — patrz **My Agents** poniżej.
</details>
<details>
<summary><b>🧑‍🚀 My Agents — Konsultuj i importuj innych agentów</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/myagents/00-overview.png" alt="Obszar roboczy My Agents DeepTutor" width="900">
</div>
My Agents zamienia innych agentów w kontekst dla DeepTutor i wykonuje dwie odrębne rzeczy. **Połącz żywego agenta** — Claude Code lub Codex CLI na twoim komputerze, lub jednego z twoich Partners — i konsultuj go z wnętrza tury czatu: DeepTutor faktycznie *uruchamia* drugiego agenta i strumieniuje jego pracę do panelu Activity przez narzędzie `consult_subagent`. Wybierz go chipem Agent (lub wpisz `@`) i ustaw ile rund może trwać konsultacja.
<div align="center">
<img src="../../assets/figs/web-1.4.6+/home/08-subagent%20demo%20with%20claude%20code.png" alt="Konsultowanie subagenta Claude Code na żywo" width="900">
</div>
**Importuj poprzednie konwersacje** — przynieś swoją istniejącą historię Claude Code i Codex jako nazwane, przeszukiwalne, wznawialne agenty. Wybierz które dni importować; odświeżanie ponownie synchronizuje je. Odwołaj się do zaimportowanej konwersacji z dowolnej tury czatu przez `+` → My Agents, a DeepTutor czyta ją jako transkrypt osoby trzeciej — pozostaje *ich* konwersacją, nie własnym głosem DeepTutor.
</details>
<details>
<summary><b>✍️ Co-Writer — Edycja Markdown z uwzględnieniem zaznaczenia</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/co-writer/00-overview.png" alt="Obszar roboczy Co-Writer DeepTutor" width="900">
</div>
Co-Writer to obszar roboczy Markdown z podzielonym widokiem dla raportów, samouczków, notatek i długich artefaktów uczenia się. Dokumenty są automatycznie zapisywane, renderują podgląd na żywo (matematyka KaTeX, schematy), i mogą być zapisane z powrotem do notatników gdy szkic staje się kontekstem wielokrotnego użytku.
<div align="center">
<img src="../../assets/figs/web-1.4.6+/co-writer/01-edit%20panel.png" alt="Edytor Co-Writer z podglądem na żywo" width="900">
</div>
Jego wyróżniającym pomysłem jest **precyzyjna edycja**: zaznacz fragment i poproś DeepTutor o przepisanie, rozszerzenie lub skrócenie. Agent edycji może ugruntować zmianę w bazie wiedzy lub dowodach webowych, zachowuje ślad swoich wywołań narzędzi i pokazuje każdą zmianę jako diff akceptuj/odrzuć — więc nic nie ląduje dopóki tego nie zatwierdzisz.
</details>
<details>
<summary><b>📖 Book — Żywe książki z twoich materiałów</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/book/00-book_overview.png" alt="Biblioteka książek DeepTutor" width="900">
</div>
Book zamienia wybrane źródła w interaktywną **żywą książkę** — nie statyczny PDF, ale środowisko czytelnicze zbudowane z typowanych bloków. Książka może zaczynać się od baz wiedzy, notatników, banków pytań lub historii czatu; przepływ tworzenia proponuje konspekt rozdziałów przed wygenerowaniem treści, więc przeglądasz kształt zamiast akceptować ślepe jednorazowe wyjście.
<p align="center">
<img src="../../assets/figs/web-1.4.6+/book/01-book-demo-quiz%20card.png" alt="Blok quizu w książce" width="31%">
&nbsp;
<img src="../../assets/figs/web-1.4.6+/book/02-book-demo-manim%20video.png" alt="Blok animacji Manim w książce" width="31%">
&nbsp;
<img src="../../assets/figs/web-1.4.6+/book/03-book-demo%20interactive%20module.png" alt="Blok interaktywnego widżetu w książce" width="31%">
</p>
Każdy rozdział kompiluje się do typowanych bloków — tekst, callouts, quizy, fiszki, osie czasu, kod, figury, interaktywny HTML, animacje, grafy konceptów, dogłębne analizy i notatki użytkownika — a każda strona ma swój własny Page Chat. Bloki są edytowalne: wstawiaj, przenoś, regeneruj lub zmieniaj typ bloku bez przepisywania rozdziału. Polecenia konserwacyjne takie jak `deeptutor book health` i `deeptutor book refresh-fingerprints` pomagają wykryć kiedy wiedza źródłowa odbiega od skompilowanych stron.
</details>
<details>
<summary><b>📚 Knowledge Center — Wielosilnikowe biblioteki RAG</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/knowledge/00-overview.png" alt="Knowledge Center DeepTutor" width="900">
</div>
Bazy wiedzy to kolekcje dokumentów za RAG — ugruntowują tury Chat, edycje Co-Writer, generowanie Book i konwersacje Partner. Wyróżnikiem jest **wybór silnika wyszukiwania**: **LlamaIndex** (domyślny, lokalny wektor + BM25), **PageIndex** (hostowany, wyszukiwanie z rozumowaniem z cytowaniami na poziomie strony), **GraphRAG** i **LightRAG** (wyszukiwanie oparte na grafach wiedzy), **LightRAG Server** (wyszukiwanie odciążone do zewnętrznej instancji LightRAG którą łączysz przez HTTP) lub podłączony vault **Obsidian** który tutor czyta i zapisuje w miejscu. Każda KB jest powiązana z jednym silnikiem.
<div align="center">
<img src="../../assets/figs/web-1.4.6+/knowledge/01-create%20knowledge%20base.png" alt="Tworzenie bazy wiedzy" width="900">
</div>
Tworząc KB, albo **tworzysz nową** (przesyłasz dokumenty i budujesz świeży indeks) albo **łączysz istniejącą** (ponownie używasz indeksu zbudowanego gdzie indziej, czytasz w miejscu bez ponownego indeksowania). Ponowne indeksowanie zapisuje nowy płaski katalog `version-N` i zachowuje poprzednie, więc działający indeks nigdy nie jest niszczony w trakcie przebudowy. Pojedynczy dokument można usunąć nawet z bazy w stanie **błędu** — usuwając plik, który nie sparsował się poprawnie, bez pełnego usuwania i przebudowy. Parsowanie dokumentów — Tylko tekst, MinerU, Docling, markitdown lub PyMuPDF4LLM — jest wybierane w **Settings → Knowledge Base**, z domyślnie wyłączonymi pobieraniami lokalnego modelu. CLI odzwierciedla cykl życia za pomocą `deeptutor kb list`, `info`, `create`, `add`, `search`, `set-default` i `delete`.
</details>
<details>
<summary><b>🌐 Learning Space — Umiejętności, persony i kontekst wielokrotnego użytku</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/learning-space/00-overview.png" alt="Centrum Learning Space DeepTutor" width="900">
</div>
Learning Space to biblioteka i warstwa personalizacji — miejsce gdzie żyją rzeczy, które się zachowują. **Conversations & Materials** przechowuje historię czatu, notatniki i bank pytań (każde zapisane pytanie zachowuje twoją odpowiedź, odpowiedź referencyjną i wyjaśnienie). **Personalization** przechowuje ścieżki opanowania, persony (presety zachowań takie jak *peer*, *research-assistant*, *teacher*) i umiejętności (podręczniki `SKILL.md` które model czyta na żądanie). Wszystko tutaj można ponownie używać z Chat, Partners, Co-Writer i Book.
<div align="center">
<img src="../../assets/figs/web-1.4.6+/learning-space/07-%20download%20skills%20from%20eduhub.png" alt="Importowanie umiejętności z EduHub" width="900">
</div>
Nie musisz pisać każdej umiejętności samodzielnie — **Import from EduHub** przegląda katalog społecznościowy i pobiera umiejętność bezpośrednio do twojej biblioteki przez bramę bezpieczeństwa (patrz [Ekosystem](#-ekosystem--eduhub-i-społeczność-umiejętności)).
</details>
<details>
<summary><b>🧠 Memory — Inspektowalna personalizacja</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/memory/00-overview.png" alt="Przegląd Memory DeepTutor" width="900">
</div>
Memory to system trzywarstwowy oparty na plikach, który możesz czytać, selekcjonować i audytować — celowo *nie* ukryty magazyn wektorowy. **L1** to lustro obszaru roboczego plus dołączany ślad zdarzeń (`trace/<surface>/<date>.jsonl`); **L2** to wyselekcjonowane fakty per-powierzchnia (`L2/<surface>.md`); **L3** to synteza między-powierzchniowa (`L3/<profile|recent|scope|preferences>.md`). Ponieważ L2 cytuje L1, a L3 cytuje L2, nic w twoim profilu nie jest nierozliczalne.
<div align="center">
<img src="../../assets/figs/web-1.4.6+/memory/01-3%20layer%20memory%20graph.png" alt="Graf pamięci DeepTutor" width="900">
</div>
Memory Graph pokazuje całą piramidę — synteza L3 w centrum, L2 w środkowym pierścieniu, ślady L1 na zewnątrz — więc możesz śledzić każde zsyntetyzowane twierdzenie z powrotem do dokładnego surowego zdarzenia za nim. Memory jest śledzone przez powierzchnie `chat`, `notebook`, `quiz`, `kb`, `book`, partner i `cowriter`; budżety Update / Audit / Dedup konsolidatora są dostosowywane w **Settings → Memory**.
</details>
<details>
<summary><b>⚙️ Settings — Jedna płaszczyzna kontroli</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/settings/00-setting%20overview.png" alt="Centrum ustawień DeepTutor" width="900">
</div>
Settings to operacyjna płaszczyzna kontroli z paskiem statusu na żywo (Backend, LLM, Embedding, Search) i jedną kartą na obszar: **Appearance** (motyw + język UI), **Network** (baza API, porty, CORS), **Models** (LLM, Embedding, Search, Text-to-Speech, Speech-to-Text, Image Generation, Video Generation), **Knowledge Base** (silnik parsowania dokumentów), **Chat** (narzędzia, serwery MCP, parametry per-możliwość), **Partners & Agents** (subagenty które możesz konsultować z tury) i **Memory** (budżety konsolidatora).
<div align="center">
<img src="../../assets/figs/web-1.4.6+/settings/01-appearance%20settings.png" alt="Ustawienia wyglądu DeepTutor i motywy" width="900">
</div>
Większość sekcji używa przepływu szkic-i-zastosuj, więc możesz testować dostawcę przed jego zatwierdzeniem. Cztery motywy dostarczane w zestawie — Default, Cream, Dark i Glass. Pliki `.env` katalogu głównego projektu są celowo ignorowane; konfiguracja środowiska uruchomieniowego żyje pod `data/user/settings/*.json` chyba że `DEEPTUTOR_HOME` lub `deeptutor start --home` wskaże aplikację gdzie indziej.
</details>
<details>
<summary><b>👥 Multi-User — Wdrożenia współdzielone</b> · opcjonalne uwierzytelnianie, izolowane obszary robocze per-użytkownik</summary>
Uwierzytelnianie jest **domyślnie wyłączone** — DeepTutor działa jednoosobowo. Włącz je a jedno drzewo `data/` obsługuje obszar roboczy administratora, izolowane obszary robocze per-użytkownik i obszary robocze partnerów obok siebie:
```text
data/
├── user/ # Obszar roboczy administratora + globalne ustawienia
├── users/<uid>/ # Zakres per-użytkownik: historia czatu, pamięć, notatniki, KB
├── partners/<id>/workspace/ # Zakres partnera (użytkownika syntetycznego)
└── system/ # auth/users.json · grants/<uid>.json · audit/usage.jsonl
```
**Pierwszy zarejestrowany użytkownik staje się administratorem** i jest właścicielem katalogów modeli, danych uwierzytelniających dostawców, współdzielonych baz wiedzy, umiejętności i uprawnień per-użytkownik. Wszyscy pozostali otrzymują izolowany obszar roboczy i zredagowaną stronę Settings — przypisane przez administratora modele, KB i umiejętności pojawiają się jako ograniczone, tylko do odczytu opcje, nigdy jako surowe klucze API.
**Włącz:** włącz uwierzytelnianie w `data/user/settings/auth.json`, uruchom ponownie `deeptutor start`, zarejestruj pierwszego administratora pod `/register`, następnie dodaj użytkowników z `/admin/users` i przypisz modele, KB, umiejętności, Partners, politykę narzędzi/MCP i dostęp do wykonania kodu przez uprawnienia.
> PocketBase pozostaje integracją jednoosobową — zostaw `integrations.pocketbase_url` puste dla wdrożeń wieloużytkownikowych chyba że podłączyłeś zewnętrzny magazyn użytkowników.
</details>
## ⌨️ DeepTutor CLI — Interfejs natywny dla agentów
Jeden plik binarny `deeptutor`, dwa sposoby wejścia: interaktywny **REPL** dla osób żyjących w terminalu i strukturalny **JSON** dla innych agentów które prowadzą DeepTutor jako narzędzie. Te same możliwości, narzędzia i bazy wiedzy w obu przypadkach.
<details>
<summary><b>Prowadź sam</b></summary>
`deeptutor chat` otwiera interaktywny REPL; `deeptutor run <capability> "<message>"` uruchamia jedną turę i wychodzi. Oba używają tych samych flag `--capability`, `--tool`, `--kb` i `--config`.
```bash
deeptutor chat # interaktywny REPL
deeptutor chat --capability deep_solve --kb my-kb --tool rag
deeptutor run chat "Explain the Fourier transform" --tool rag --kb textbook
deeptutor run deep_research "Survey 2026 papers on RAG" \
--config mode=report --config depth=standard
```
Wszystko co robi aplikacja Web jest tu dostępne — bazy wiedzy (`kb`), sesje (`session`), partnerzy (`partner`), umiejętności (`skill`), notatniki, pamięć i konfiguracja. Pełna lista poniżej.
</details>
<details>
<summary><b>Niech agent prowadzi</b></summary>
DeepTutor jest zbudowany aby być *obsługiwany przez innego agenta*. Dodaj `--format json` do dowolnego `run` a każda tura strumieniuje **NDJSON — jedno zdarzenie na linię** (`content`, `tool_call`, `tool_result`, `done`, …), każda linia oznaczona swoim `session_id`. Uruchomienia są bezpieczne bez TTY: pauza `ask_user` bez TTY automatycznie rozwiązuje się pustą odpowiedzią zamiast zawieszać.
```bash
# Jednorazowo, czytelne maszynowo
deeptutor run deep_solve "Find d/dx[sin(x^2)]" --tool reason --format json
# Łącz tury w jednej sesji stanowej — przechwyć id, ponownie użyj
SID=$(deeptutor run deep_research "Survey 2026 papers on RAG" \
--config mode=report --config depth=standard --format json \
| jq -r 'select(.type=="done").session_id')
deeptutor run deep_question "Quiz me on that survey" --session "$SID" --format json
```
Repozytorium zawiera główny [`SKILL.md`](../../SKILL.md) — około 150-liniowy dokument przekazania który uczy każdy LLM używający narzędzi całej powierzchni w jednym czytaniu. Przekaż go Claude Code, Codex lub OpenCode (automatycznie pobierają `SKILL.md`) lub opakuj `deeptutor run` jako narzędzie w pętli LangChain / AutoGen. Pełne przepisy: [Agent Handoff](https://deeptutor.info/docs/cli/agent-handoff/).
</details>
<details>
<summary><b>Odniesienie do poleceń</b></summary>
| Polecenie | Opis |
|:---|:---|
| `deeptutor init` | Utwórz lub zaktualizuj `data/user/settings` dla bieżącego obszaru roboczego |
| `deeptutor start [--home PATH]` | Uruchom backend + frontend razem |
| `deeptutor serve [--port PORT]` | Uruchom tylko backend FastAPI |
| `deeptutor run <capability> <message>` | Uruchom jedną turę możliwości (`chat`, `deep_solve`, `deep_question`, `deep_research`, `visualize`, `math_animator`, `mastery_path`); dodaj `--format json` dla wyjścia NDJSON |
| `deeptutor chat` | Interaktywny REPL z kontrolkami możliwości, narzędzia, KB, notatnika i historii |
| `deeptutor partner list/create/start/stop` | Zarządzaj partnerami połączonymi przez IM |
| `deeptutor kb list/info/create/add/search/set-default/delete` | Zarządzaj bazami wiedzy LlamaIndex |
| `deeptutor skill search/install/list/remove/login/logout/publish/update` | Zarządzaj umiejętnościami, instaluj z hubów i publikuj własne (`eduhub:<slug>` domyślnie, patrz Ekosystem) |
| `deeptutor memory show/clear` | Inspekcjonuj dokumenty pamięci L2/L3 lub wyczyść pamięć L1/wszystko |
| `deeptutor session list/show/open/rename/delete` | Zarządzaj współdzielonymi sesjami |
| `deeptutor notebook list/create/show/add-md/replace-md/remove-record` | Zarządzaj notatnikami z plików Markdown |
| `deeptutor book list/health/refresh-fingerprints` | Inspekcjonuj książki i odświeżaj odciski źródeł |
| `deeptutor plugin list/info` | Inspekcjonuj zarejestrowane narzędzia i możliwości |
| `deeptutor config show` | Wydrukuj podsumowanie konfiguracji |
| `deeptutor provider login <provider>` | Uwierzytelnianie dostawcy (`openai-codex` logowanie OAuth; `github-copilot` weryfikuje istniejącą sesję auth Copilot) |
</details>
<details>
<summary><b>Dystrybucja tylko CLI</b></summary>
Pakiet tylko CLI żyje w `packaging/deeptutor-cli`. W tym kodzie źródłowym zainstaluj go ze źródła:
```bash
python -m pip install -e ./packaging/deeptutor-cli
```
Nie jest jeszcze opublikowany na PyPI, więc główna sekcja [Pierwsze kroki](#-pierwsze-kroki) zachowuje ścieżkę instalacji ze źródła.
</details>
## 🧩 Ekosystem — EduHub i społeczność umiejętności
Umiejętności DeepTutor używają otwartego formatu **Agent-Skills** — folder z podręcznikiem `SKILL.md` (frontmatter YAML + Markdown) i opcjonalnymi plikami referencyjnymi. Nic w tym nie jest specyficzne dla DeepTutor, więc każdy rejestr który mówi w tym formacie staje się źródłem dla twojej biblioteki. DeepTutor jest dostarczany z **[EduHub](https://eduhub.deeptutor.info/)** — naszym własnym rejestrem umiejętności skupionym na edukacji — podłączonym jako domyślny hub.
<details>
<summary><b>EduHub — Ekosystem umiejętności DeepTutor</b></summary>
[**EduHub**](https://eduhub.deeptutor.info/) to hub społecznościowy który DeepTutor uruchomił do dzielenia się umiejętnościami agentów zorientowanymi na nauczanie — tutorzy sokratejscy, kreatory fiszek, informacje zwrotne na eseje, plany egzaminów, objaśniacze konceptów i więcej. Jest wbudowany w DeepTutor, więc nie ma nic do konfigurowania: gołe slug lub prefiks `eduhub:` rozwiązuje do niego.
**Znajdź i zainstaluj** — w przeglądarce otwórz **Learning Space → Skills → Import from EduHub** aby przeglądać katalog i pobrać umiejętność bezpośrednio do swojej biblioteki. Z terminala:
```bash
deeptutor skill search "socratic tutor" # wyszukaj EduHub (domyślny hub)
deeptutor skill install socratic-tutor # pobierz → weryfikuj → zarejestruj
deeptutor skill install eduhub:socratic-tutor@1.2.0 # przypnij hub i wersję
deeptutor skill list # lokalne umiejętności z proweniencją hubu
```
**Opublikuj własną** — spakuj `SKILL.md` i podziel się ze społecznością:
```bash
deeptutor skill login # logowanie przeglądarki do EduHub
deeptutor skill publish ./my-skill # interaktywne: wybierz ścieżkę + tagi, następnie prześlij
deeptutor skill update # wycofaj lub wydaj nową wersję
```
EduHub jest również samodzielnym, kompatybilnym z ClawHub rejestrem, więc agenty które nie są DeepTutorem (Claude Code, Codex, …) mogą używać go bezpośrednio przez CLI `eduhub``npx eduhub install socratic-tutor`.
</details>
<details>
<summary><b>Brama bezpieczeństwa importu</b></summary>
Niezależnie od źródła, każdy import przechodzi przez tę samą **bramę bezpieczeństwa** zanim cokolwiek dotknie twojego obszaru roboczego:
- **werdykt bezpieczeństwa** rejestru jest sprawdzany jako pierwszy — oznaczone pakiety są odrzucane chyba że przekażesz `--allow-unverified`;
- archiwa są ekstraktowane defensywnie (ochrona przed zip-slip / zip-bomb) za **białą listą sufiksów** tekst/skrypt, więc pliki binarne nigdy nie lądują w obszarze roboczym;
- frontmatter jest normalizowany do schematu DeepTutor a `always:` jest **usuwane**, więc pobrana umiejętność nigdy nie może wymusić się do każdego systemowego promptu;
- proweniencja — hub, wersja, werdykt i czas instalacji — jest zapisywana do `.hub-lock.json` dla audytów i aktualizacji.
W wdrożeniach wieloużytkownikowych, instalowanie jest tylko dla administratorów: nowa umiejętność ląduje w katalogu administratora i pozostaje niewidoczna dla innych użytkowników dopóki uprawnienie jej nie przypisze, więc administrator może ją sprawdzić przed wdrożeniem.
</details>
<details>
<summary><b>Kompatybilność z ClawHub</b></summary>
Ponieważ DeepTutor mówi otwartym formatem Agent-Skills, **[ClawHub](https://clawhub.ai/)** działa również jako pierwszorzędne źródło — jest wbudowany obok EduHub. Wybierz go z prefiksem hubu:
```bash
deeptutor skill search "git release notes" --hub clawhub
deeptutor skill install clawhub:git-release-notes@1.0.1
```
Dodaj więcej rejestrów w `settings/skill_hubs.json`: wpis `type: "clawhub"` wskazuje na dowolne kompatybilne HTTP API (EduHub i ClawHub oba je mówią), `type: "command"` opakowuje dowolny CLI pobierania który rejestr dostarcza i `"default"` wybiera hub używany dla gołych slugów. Wszystkie zasilają tę samą bramę importu.
</details>
## 🌐 Społeczność
### 📮 Kontakt
DeepTutor to projekt open-source prowadzony przez [Bingxi Zhao](https://github.com/pancacake) w ramach Grupy [HKUDS](https://github.com/HKUDS), i iteruje w **w pełni open-source formie**, budowany razem ze społecznością. Do tej pory **NIE** mamy żadnych płatnych produktów online jakiegokolwiek rodzaju. Zapraszamy do kontaktu pod adresem **bingxizhao39@gmail.com** w sprawie dyskusji, pomysłów lub współpracy.
### 🙏 Podziękowania
Serdeczne podziękowania dla [**Chao Huang**](https://sites.google.com/view/chaoh), dyrektora Data Intelligence Lab @ HKU, i naszych współpracowników z HKUDS za ciepłe wsparcie — szczególnie [**Jiahao Zhang**](https://github.com/zzhtx258), [**Zirui Guo**](https://github.com/LarFii) i [**Xubin Ren**](https://github.com/Re-bin). Jesteśmy również głęboko wdzięczni **społeczności open-source**: wasze gwiazdki, zgłoszenia, pull requesty i dyskusje kształtują DeepTutor każdego dnia.
DeepTutor stoi również na ramionach wybitnych projektów open-source które dostarczyły nam zarówno narzędzia jak i inspirację:
| Projekt | Rola / Inspiracja |
|:---|:---|
| [**LlamaIndex**](https://github.com/run-llama/llama_index) | Kręgosłup potoku RAG i indeksowania dokumentów |
| [**nanobot**](https://github.com/HKUDS/nanobot) | Ultralekki silnik agenta który zasilał oryginalny TutorBot *(HKUDS)* |
| [**LightRAG**](https://github.com/HKUDS/LightRAG) | Prosty i szybki RAG *(HKUDS)* |
| [**AutoAgent**](https://github.com/HKUDS/AutoAgent) | Framework agentów bez kodu *(HKUDS)* |
| [**AI-Researcher**](https://github.com/HKUDS/AI-Researcher) | Zautomatyzowany potok badań naukowych *(HKUDS)* |
| [**OpenClaw**](https://github.com/openclaw/openclaw) | Otwarta brama agentów i ekosystem umiejętności za ClawHub |
| [**Codex**](https://github.com/openai/codex) | Natywny dla agentów CLI kodowania który zainspirował nasz przepływ pracy CLI |
| [**Claude Code**](https://github.com/anthropics/claude-code) | Agentowy CLI kodowania który zainspirował pętlę agenta DeepTutor |
| [**ManimCat**](https://github.com/Wing900/ManimCat) | Generowanie animacji matematycznych sterowane AI dla Math Animator |
### 🗺️ Plan działania i współtworzenie
Chcemy aby DeepTutor stale iterował i się rozwijał — a ostatecznie stał się prezentem który oddajemy społeczności open-source. Nasz [**plan działania**](https://github.com/HKUDS/DeepTutor/issues/498) jest aktualizowany na bieżąco; głosuj na elementy tam lub proponuj nowe. Jeśli chcesz współtworzyć, zapoznaj się z [**Przewodnikiem dla współtwórców**](../../CONTRIBUTING.md) po strategię gałęzi, standardy kodowania i sposób rozpoczęcia.
<div align="center">
Mamy nadzieję, że DeepTutor stanie się prezentem dla społeczności. 🎁
<a href="https://github.com/HKUDS/DeepTutor/graphs/contributors">
<img src="https://contrib.rocks/image?repo=HKUDS/DeepTutor&max=999" alt="Współtwórcy" />
</a>
</div>
<div align="center">
<a href="https://www.star-history.com/#HKUDS/DeepTutor&type=timeline&legend=top-left">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=HKUDS/DeepTutor&type=timeline&theme=dark&legend=top-left" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=HKUDS/DeepTutor&type=timeline&legend=top-left" />
<img alt="Wykres historii gwiazdek" src="https://api.star-history.com/svg?repos=HKUDS/DeepTutor&type=timeline&legend=top-left" />
</picture>
</a>
</div>
<p align="center">
<a href="https://www.star-history.com/hkuds/deeptutor">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/badge?repo=HKUDS/DeepTutor&theme=dark" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/badge?repo=HKUDS/DeepTutor" />
<img alt="Ranking historii gwiazdek" src="https://api.star-history.com/badge?repo=HKUDS/DeepTutor" />
</picture>
</a>
</p>
<div align="center">
Licencjonowany na podstawie [Apache License 2.0](../../LICENSE).
<p>
<img src="https://visitor-badge.laobi.icu/badge?page_id=HKUDS.DeepTutor&style=for-the-badge&color=00d4ff" alt="Odwiedziny">
</p>
</div>
+719
View File
@@ -0,0 +1,719 @@
<div align="center">
<p align="center"><img src="../../assets/figs/logo/logo.png" alt="DeepTutor logo" height="56" style="vertical-align: middle;">&nbsp;<img src="../../assets/figs/logo/banner.png" alt="DeepTutor" height="48" style="vertical-align: middle;"></p>
# DeepTutor: Tutoria Personalizada Vitalícia
<p align="center">
<a href="https://deeptutor.info" target="_blank"><img alt="Docs — deeptutor.info" src="https://img.shields.io/badge/Docs-deeptutor.info%20%E2%86%97-0A0A0A?style=for-the-badge&labelColor=F5F5F4" height="36"></a>
</p>
<p align="center">
<a href="https://trendshift.io/repositories/17099?utm_source=repository-badge&amp;utm_medium=badge&amp;utm_campaign=badge-repository-17099" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/repositories/17099" alt="HKUDS%2FDeepTutor | Trendshift" width="250" height="55"/></a>&nbsp;
<a href="https://trendshift.io/repositories/17099?utm_source=trendshift-badge&amp;utm_medium=badge&amp;utm_campaign=badge-trendshift-17099" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/17099/daily" alt="HKUDS%2FDeepTutor | Trendshift" width="250" height="55"/></a>&nbsp;
<a href="https://trendshift.io/repositories/17099?utm_source=trendshift-badge&amp;utm_medium=badge&amp;utm_campaign=badge-trendshift-17099" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/17099/weekly?language=Python" alt="HKUDS%2FDeepTutor | Trendshift" width="250" height="55"/></a>
</p>
<p align="center">
<a href="../../README.md"><img alt="English" height="40" src="https://img.shields.io/badge/English-CDCFD4"></a>&nbsp;
<a href="README_CN.md"><img alt="简体中文" height="40" src="https://img.shields.io/badge/简体中文-CDCFD4"></a>&nbsp;
<a href="README_JA.md"><img alt="日本語" height="40" src="https://img.shields.io/badge/日本語-CDCFD4"></a>&nbsp;
<a href="README_ES.md"><img alt="Español" height="40" src="https://img.shields.io/badge/Español-CDCFD4"></a>&nbsp;
<a href="README_FR.md"><img alt="Français" height="40" src="https://img.shields.io/badge/Français-CDCFD4"></a>&nbsp;
<a href="README_AR.md"><img alt="Arabic" height="40" src="https://img.shields.io/badge/Arabic-CDCFD4"></a>&nbsp;
<a href="README_RU.md"><img alt="Русский" height="40" src="https://img.shields.io/badge/Русский-CDCFD4"></a>&nbsp;
<a href="README_HI.md"><img alt="Hindi" height="40" src="https://img.shields.io/badge/Hindi-CDCFD4"></a>&nbsp;
<a href="README_PT.md"><img alt="Português" height="40" src="https://img.shields.io/badge/Português-BCDCF7"></a>&nbsp;
<a href="README_TH.md"><img alt="Thai" height="40" src="https://img.shields.io/badge/Thai-CDCFD4"></a>&nbsp;
<a href="README_PL.md"><img alt="Polski" height="40" src="https://img.shields.io/badge/Polski-CDCFD4"></a>
</p>
[![Python 3.11+](https://img.shields.io/badge/Python-3.11%2B-3776AB?style=flat-square&logo=python&logoColor=white)](https://www.python.org/downloads/)
[![Next.js 16](https://img.shields.io/badge/Next.js-16-000000?style=flat-square&logo=next.js&logoColor=white)](https://nextjs.org/)
[![License](https://img.shields.io/badge/License-Apache_2.0-blue?style=flat-square)](../../LICENSE)
[![GitHub release](https://img.shields.io/github/v/release/HKUDS/DeepTutor?style=flat-square&color=brightgreen)](https://github.com/HKUDS/DeepTutor/releases)
[![arXiv](https://img.shields.io/badge/arXiv-2604.26962-b31b1b?style=flat-square&logo=arxiv&logoColor=white)](https://arxiv.org/abs/2604.26962)
[![Discord](https://img.shields.io/badge/Discord-Community-5865F2?style=flat-square&logo=discord&logoColor=white)](https://discord.gg/eRsjPgMU4t)
[![Feishu](https://img.shields.io/badge/Feishu-Group-00D4AA?style=flat-square&logo=feishu&logoColor=white)](../../Communication.md)
[![WeChat](https://img.shields.io/badge/WeChat-Group-07C160?style=flat-square&logo=wechat&logoColor=white)](https://github.com/HKUDS/DeepTutor/issues/78)
[Recursos](#-recursos-principais) · [Começar](#-começar) · [Explorar](#-explorar-o-deeptutor) · [CLI](#-deeptutor-cli--interface-nativa-de-agentes) · [Ecossistema](#-ecossistema--eduhub-e-a-comunidade-de-skills) · [Comunidade](#-comunidade)
</div>
---
> 🤝 **Damos as boas-vindas a todo tipo de contribuições!** Vote em itens do roadmap ou proponha novos em [`Roadmap`](https://github.com/HKUDS/DeepTutor/issues/498), e consulte o nosso [Guia de Contribuição](../../CONTRIBUTING.md) para a estratégia de branches, padrões de código e como começar.
### 📰 Notícias
- **2026-05-22** 🌐 Site oficial de documentação disponível em [**deeptutor.info**](https://deeptutor.info/) — guias, referências e tours de capacidades num só lugar.
- **2026-04-19** 🎉 Atingimos 20k estrelas em 111 dias! Obrigado pelo apoio incrível rumo a uma tutoria verdadeiramente personalizada e inteligente para todos.
- **2026-04-10** 📄 O nosso artigo está agora no arXiv! Leia o [preprint](https://arxiv.org/abs/2604.26962) para saber mais sobre o design e as ideias por trás do DeepTutor.
- **2026-02-06** 🚀 Atingimos 10k estrelas em apenas 39 dias! Um enorme obrigado à nossa incrível comunidade pelo apoio!
- **2026-01-01** 🎊 Feliz Ano Novo! Junte-se ao nosso [Discord](https://discord.gg/eRsjPgMU4t), [WeChat](https://github.com/HKUDS/DeepTutor/issues/78) ou [Discussions](https://github.com/HKUDS/DeepTutor/discussions) — juntos damos forma ao futuro do DeepTutor!
- **2025-12-29** 🎓 DeepTutor está oficialmente lançado!
## ✨ Recursos Principais
O DeepTutor é um espaço de trabalho de aprendizagem nativo de agentes que conecta tutoria, resolução de problemas, geração de quizzes, pesquisa, visualização e prática de domínio num sistema extensível.
- **Um runtime para todos os modos** — Chat, Quiz, Research, Visualize, Solve e Mastery Path correm no mesmo loop de agente, pelo que muda o objetivo, não o motor, e o contexto acompanha o utilizador.
- **Contexto de aprendizado conectado** — bases de conhecimento, livros, rascunhos Co-Writer, cadernos, bancos de questões, personas e Memory permanecem disponíveis em todos os fluxos de trabalho em vez de viverem em ferramentas isoladas.
- **Subagentes e Partners** — consultar um Claude Code, Codex ou Partner ao vivo a partir de qualquer turno (ou importar as suas conversas anteriores), e correr companheiros IM persistentes no mesmo cérebro.
- **Conhecimento multi-motor** — bibliotecas RAG com versões: LlamaIndex, PageIndex, GraphRAG, LightRAG ou um vault Obsidian vinculado, com análise de documentos conectável.
- **Ferramentas e habilidades extensíveis** — ferramentas integradas, servidores MCP, modelos de geração de imagem / vídeo / voz e habilidades da comunidade instaláveis do EduHub.
- **Memória inspecionável** — rastreamentos L1, resumos de superfície L2 e síntese L3 tornam a personalização visível e editável, com um Memory Graph que rastreia cada afirmação até à sua evidência.
---
## 🚀 Começar
O DeepTutor inclui quatro caminhos de instalação. Todos partilham um layout de espaço de trabalho: as configurações vivem em `data/user/settings/` sob o diretório a partir do qual é iniciado (ou sob `DEEPTUTOR_HOME` / `deeptutor start --home` se definido explicitamente). Para a aplicação completa, o fluxo recomendado é **escolher um diretório de espaço de trabalho → instalar → `deeptutor init` → `deeptutor start`**.
<details>
<summary><b>Opção 1 — Instalar a partir do PyPI</b> · aplicação web local completa + CLI, sem necessidade de clonar</summary>
Aplicação web local completa + CLI, sem necessidade de clonar. Requer **Python 3.11+** e um runtime **Node.js 20+** no PATH (o servidor standalone Next.js empacotado é iniciado por `deeptutor start`).
```bash
mkdir -p my-deeptutor && cd my-deeptutor
pip install -U deeptutor
deeptutor init # solicita portas + provedor LLM + embedding opcional
deeptutor start # inicia backend + frontend; manter o terminal aberto
```
`deeptutor init` solicita a porta de backend (predefinição `8001`), a porta de frontend (predefinição `3782`), provedor LLM / URL base / chave API / modelo e um provedor de embeddings opcional para Base de Conhecimento / RAG.
Após `deeptutor start`, abra a URL do frontend impressa no terminal — por predefinição [http://127.0.0.1:3782](http://127.0.0.1:3782). Prima `Ctrl+C` nesse terminal para parar tanto o backend como o frontend. Omitir `deeptutor init` é adequado para um teste rápido; a aplicação arranca com portas predefinidas e configuração de modelo vazia, configure-as depois em **Settings → Models**.
</details>
<details>
<summary><b>Opção 2 — Instalar a partir do Código-Fonte</b> · desenvolver num checkout</summary>
Para desenvolvimento num checkout. Use **Python 3.11+** e **Node.js 22 LTS** para coincidir com CI e Docker.
```bash
git clone https://github.com/HKUDS/DeepTutor.git
cd DeepTutor
# Criar um venv (macOS/Linux). Windows PowerShell:
# py -3.11 -m venv .venv ; .\.venv\Scripts\Activate.ps1
python3 -m venv .venv && source .venv/bin/activate
python -m pip install --upgrade pip
# Instalar dependências de backend + frontend
python -m pip install -e .
( cd web && npm ci --legacy-peer-deps )
deeptutor init
deeptutor start
```
As instalações a partir de fonte executam o Next.js em modo de desenvolvimento contra o diretório `web/` local; todo o resto (layout de configuração, portas, parar com `Ctrl+C`) corresponde à Opção 1.
<details>
<summary><b>Ambiente Conda</b> (em vez de <code>venv</code>)</summary>
```bash
conda create -n deeptutor python=3.11
conda activate deeptutor
python -m pip install --upgrade pip
```
</details>
<details>
<summary><b>Extras de instalação opcionais</b> — dev / partners / matrix / math-animator</summary>
```bash
pip install -e ".[dev]" # ferramentas de testes/lint
pip install -e ".[partners]" # SDKs de canais IM de Partners + cliente MCP
pip install -e ".[matrix]" # canal Matrix sem E2EE/libolm
pip install -e ".[matrix-e2e]" # Matrix E2EE; requer libolm
pip install -e ".[math-animator]" # add-on Manim; requer LaTeX/ffmpeg/libs do sistema
```
</details>
<details>
<summary><b>Ajustes de dependências do frontend e resolução de problemas do servidor de desenvolvimento</b></summary>
**Alterar dependências do frontend:** execute `npm install --legacy-peer-deps` para atualizar `web/package-lock.json`, depois confirme tanto `web/package.json` como `web/package-lock.json`.
**Servidor de desenvolvimento bloqueado:** se `deeptutor start` reportar um frontend existente que não responde, pare o PID que imprime. Se não houver nenhum processo Next.js em execução, os ficheiros de bloqueio estão desatualizados — remova-os e tente novamente:
```bash
rm -f web/.next/dev/lock web/.next/lock
deeptutor start
```
</details>
</details>
<details>
<summary><b>Opção 3 — Docker</b> · um contentor autossuficiente</summary>
Um contentor para a aplicação web completa. Imagens no GitHub Container Registry:
- `ghcr.io/hkuds/deeptutor:latest` — lançamento estável
- `ghcr.io/hkuds/deeptutor:pre` — pré-lançamento, quando disponível
> Consulte [CONTAINERIZATION.md](../../CONTAINERIZATION.md) para implementações podman/rootless/read-only-rootfs e o guia completo por instalação.
```bash
docker run --rm --name deeptutor \
-p 127.0.0.1:3782:3782 \
-v deeptutor-data:/app/data \
ghcr.io/hkuds/deeptutor:latest
```
> **Apenas `3782` precisa de ser publicado.** O navegador comunica exclusivamente com a origem do frontend; o middleware Next.js (`web/proxy.ts`) reencaminha `/api/*` e `/ws/*` para o backend FastAPI **dentro do contentor**. Publicar `8001` (`-p 127.0.0.1:8001:8001`) é opcional — útil apenas para aceder à API diretamente com curl ou scripts.
Abra [http://127.0.0.1:3782](http://127.0.0.1:3782). O contentor cria `/app/data/user/settings/*.json` no primeiro arranque; configure os provedores de modelos a partir da página de Settings web. A configuração, as chaves API, os logs, os ficheiros do espaço de trabalho, a memória e as bases de conhecimento persistem no volume `deeptutor-data`.
- **Portas de host diferentes:** altere o lado esquerdo de cada mapeamento `-p host:container` (ex. `-p 127.0.0.1:8088:3782`). Se alterar as portas do lado do contentor em `/app/data/user/settings/system.json`, reinicie e atualize o lado direito de cada mapeamento para corresponder.
- **Desconectado:** adicione `-d`, depois `docker logs -f deeptutor` para seguir, `docker stop deeptutor` para parar, `docker rm deeptutor` antes de reutilizar o nome. O volume `deeptutor-data` mantém as suas configurações e espaço de trabalho entre reinicializações.
**Docker remoto / proxy inverso:** o navegador comunica apenas com a origem do frontend (`:3782`); o middleware Next.js dentro do contentor reencaminha `/api/*` e `/ws/*` para o servidor de backend do lado do servidor. Para o caso comum de contentor único, não configura uma base de API — apenas aponte o seu proxy inverso / terminador TLS para `:3782`. Só precisa de uma base de API para uma **implementação separada** (backend num contentor/host separado): defina `next_public_api_base` em `data/user/settings/system.json` para o endereço interno que o servidor frontend usa para alcançar o backend (é lido do lado do servidor, nunca enviado ao navegador).
```json
{
"next_public_api_base": "http://backend:8001"
}
```
`next_public_api_base_external` (e o seu alias `public_api_base`) são aceites como fallbacks de menor precedência. CORS usa **origens** de frontend, não URLs de API. Com a autenticação desativada, o DeepTutor permite origens normais de navegador HTTP/HTTPS por predefinição. Com a autenticação ativada, adicione as origens exatas do frontend:
```json
{
"cors_origins": ["https://deeptutor.example.com"]
}
```
<details>
<summary><b>Ligar ao Ollama / LM Studio / llama.cpp / vLLM / Lemonade no host</b></summary>
Dentro do Docker, `localhost` é o próprio contentor, não a sua máquina host. Para alcançar um serviço de modelo em execução no host, use o host gateway (recomendado):
```bash
docker run --rm --name deeptutor \
-p 127.0.0.1:3782:3782 -p 127.0.0.1:8001:8001 \
--add-host=host.docker.internal:host-gateway \
-v deeptutor-data:/app/data \
ghcr.io/hkuds/deeptutor:latest
```
Depois em **Settings → Models**, aponte o URL Base do provedor para `host.docker.internal`:
- Ollama LLM: `http://host.docker.internal:11434/v1`
- Ollama embedding: `http://host.docker.internal:11434/api/embed`
- LM Studio: `http://host.docker.internal:1234/v1`
- llama.cpp: `http://host.docker.internal:8080/v1`
- Lemonade: `http://host.docker.internal:13305/api/v1`
O Docker Desktop (macOS/Windows) geralmente resolve `host.docker.internal` sem `--add-host`. No Linux, o flag é a forma portátil de criar esse nome de host no Docker Engine moderno.
**Alternativa para Linux — rede do host:** adicione `--network=host` e remova os flags `-p`. O contentor partilha a rede do host diretamente, por isso abra [http://127.0.0.1:3782](http://127.0.0.1:3782) (ou o `frontend_port` em `system.json`), e os serviços do host podem ser alcançados com URLs de localhost normais como `http://127.0.0.1:11434/v1`. Note que a rede do host expõe as portas do contentor diretamente no host e pode entrar em conflito com serviços existentes — para os manter no loopback, defina `BACKEND_HOST=127.0.0.1` e `FRONTEND_HOST=127.0.0.1` (consulte [CONTAINERIZATION.md](../../CONTAINERIZATION.md)).
</details>
</details>
<details>
<summary><b>Opção 4 — Apenas CLI</b> · sem UI web, a partir de um checkout de fonte</summary>
Quando não precisa da UI web. O pacote de apenas CLI é instalado a partir de um checkout de fonte, não a partir do PyPI.
```bash
git clone https://github.com/HKUDS/DeepTutor.git
cd DeepTutor
# Criar um venv (macOS/Linux). Windows PowerShell:
# py -3.11 -m venv .venv-cli ; .\.venv-cli\Scripts\Activate.ps1
python3 -m venv .venv-cli && source .venv-cli/bin/activate
python -m pip install --upgrade pip
python -m pip install -e ./packaging/deeptutor-cli
deeptutor init --cli
deeptutor chat
```
`deeptutor init --cli` partilha o mesmo layout `data/user/settings/` que a aplicação completa mas omite as solicitações de portas de backend/frontend e define embeddings como **desativado** (escolha `Yes` se planear usar `deeptutor kb …` ou ferramentas RAG). Ainda escreve um layout de runtime completo (`system.json`, `auth.json`, `integrations.json`, `model_catalog.json`, `main.yaml`, `agents.yaml`) e ainda solicita o provedor LLM e modelo ativos.
<details>
<summary><b>Comandos comuns</b></summary>
```bash
deeptutor chat # REPL interativo
deeptutor chat --capability deep_solve --tool rag --kb my-kb
deeptutor run chat "Explain Fourier transform"
deeptutor run deep_solve "Solve x^2 = 4" --tool rag --kb my-kb
deeptutor kb create my-kb --doc textbook.pdf
deeptutor memory show
deeptutor config show
```
</details>
A instalação local de `deeptutor-cli` não inclui ativos web nem dependências de servidor. Mantenha o checkout de fonte por perto — a instalação editável aponta para ele. Para adicionar a aplicação web mais tarde, instale o pacote PyPI (Opção 1) e execute `deeptutor init` + `deeptutor start` a partir do mesmo espaço de trabalho.
</details>
<details>
<summary><b>Sandbox de Execução de Código (skills de escritório)</b> · executar código gerado pelo modelo para docx / pdf / pptx / xlsx</summary>
As skills de escritório integradas — **docx / pdf / pptx / xlsx** — funcionam fazendo com que o
modelo escreva um script Python curto (`python-docx`, `reportlab`, `openpyxl`, …),
o execute através das ferramentas `exec` / `code_execution` e devolva um URL de download.
Essas ferramentas montam sempre que um backend de sandbox está ativo, o que é o caso **por predefinição**
em cada forma de implementação:
- **Local (Opção 1 / 2) e Docker (Opção 3, contentor único):** um sandbox de subprocesso restrito
executa o código do modelo (localmente no host, ou dentro do contentor sob Docker — o contentor
sendo o seu próprio limite de isolamento).
- **docker-compose:** encaminhado em vez disso para um **sidecar runner** endurecido e com privilégios
mínimos (`Dockerfile.runner`) via `DEEPTUTOR_SANDBOX_RUNNER_URL` — a postura mais sólida,
e preferida automaticamente quando presente.
O sandbox de subprocesso é controlado pela configuração `sandbox_allow_subprocess` em
`data/user/settings/system.json` (predefinição `true`). Executar código gerado pelo modelo no seu host
é uma decisão real de confiança — defina-o como `false` (ou exporte
`DEEPTUTOR_SANDBOX_ALLOW_SUBPROCESS=0`) para desativar a execução do lado do host, à custa das
skills de escritório já não conseguirem produzir ficheiros.
</details>
<details>
<summary><b>Referência de configuração</b> — ficheiros de configuração sob <code>data/user/settings/</code> (JSON/YAML)</summary>
Tudo sob `data/user/settings/` é JSON/YAML simples. A página **Settings** no navegador é o editor recomendado.
| Ficheiro | Propósito |
|:---|:---|
| `model_catalog.json` | Perfis de provedores LLM, embeddings e pesquisa; chaves API; modelos ativos |
| `system.json` | Portas de backend/frontend, base de API pública, CORS, verificação SSL, diretório de anexos |
| `auth.json` | Interruptor de autenticação opcional, nome de utilizador, hash de palavra-passe, configurações de token/cookie |
| `integrations.json` | Configurações opcionais de PocketBase e integrações sidecar |
| `interface.json` | Preferências de idioma / tema / barra lateral da UI |
| `main.yaml` | Predefinições de comportamento de runtime e injeção de caminhos |
| `agents.yaml` | Configurações de temperatura e tokens de capacidades/ferramentas |
O `.env` da raiz do projeto **não** é lido como ficheiro de configuração da aplicação. Para uma configuração mínima do modelo, abra **Settings → Models**, adicione um perfil LLM (URL Base / chave API / nome do modelo) e guarde. Adicione um perfil de embeddings apenas se planear usar funcionalidades de Base de Conhecimento / RAG.
</details>
## 📖 Explorar o DeepTutor
Comece pelas superfícies principais que usará no dia a dia: Chat, Partners, Meus Agentes, Co-Writer, Book, Centro de Conhecimento, Espaço de Aprendizado, Memory e Configurações. O tour cobre também as implementações Multi-Utilizador para espaços de trabalho partilhados e isolados.
<div align="center">
<img src="../../assets/figs/web-1.4.6+/OVERVIEW.png" alt="DeepTutor home — o espaço de trabalho Chat com todas as superfícies na barra lateral" width="900">
</div>
<details>
<summary><b>🏗️ Arquitetura do sistema</b></summary>
<div align="center">
<img src="../../assets/figs/system/system%20architecture.png" alt="Arquitetura do sistema DeepTutor" width="900">
</div>
</details>
<details>
<summary><b>💬 Chat — O Loop de Agente que Realmente Usa</b></summary>
Chat é a capacidade predefinida e o lugar onde a maior parte do trabalho começa. Um único thread pode conversar normalmente, chamar ferramentas, fundamentar-se em bases de conhecimento selecionadas, ler anexos, gerar imagens, consultar subagentes, escrever registos de notebook e continuar com o mesmo contexto entre turnos.
<div align="center">
<img src="../../assets/figs/web-1.4.6+/home/00-overview.png" alt="Espaço de trabalho de chat DeepTutor" width="900">
</div>
O loop é deliberadamente simples: o modelo pensa em rondas, chama ferramentas quando útil, observa os resultados e termina com uma mensagem sem ferramentas. `ask_user` é especial — em vez de adivinhar, o agente pode pausar o turno, fazer uma pergunta de esclarecimento estruturada e retomar assim que responder.
<div align="center">
<img src="../../assets/figs/system/chat-agent-loop.png" alt="Loop de agente de chat DeepTutor" width="900">
</div>
As ferramentas ativáveis pelo utilizador são `brainstorm`, `web_search`, `paper_search`, `reason` e `geogebra_analysis` — mais `imagegen` e `videogen` depois de configurar o modelo de geração correspondente. Ferramentas contextuais como `rag`, `read_source`, `read_memory`, `write_memory`, `read_skill`, `load_tools`, `exec`, `web_fetch`, `ask_user`, `list_notebook`, `write_note`, `github` e `consult_subagent` montam automaticamente quando o turno tem o contexto certo.
O contexto é de dois tipos: **contexto de sessão fixo** (subagente, bases de conhecimento, persona, modelo, voz) vive na barra de ferramentas do compositor e persiste entre turnos; **referências únicas** (ficheiros, histórico de chat, livros, notebooks, banco de questões, agentes importados) vêm do menu `+` para um único turno.
Chat é também o ponto de lançamento para capacidades mais profundas: **Quiz** para geração de perguntas, **Research** para relatórios com citações, **Visualize** para gráficos / diagramas / animações, e — em *More Capabilities***Solve** para raciocínio trabalhado e **Mastery Path** para fluxos de planos de aprendizagem.
</details>
<details>
<summary><b>🤝 Partner — Companheiros Persistentes no Mesmo Cérebro</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/partners/00-partners%20overview.png" alt="Espaço de trabalho de partners DeepTutor" width="900">
</div>
Os Partners são companheiros persistentes com a sua própria alma, política de modelo, biblioteca, memória e canais. Não são um motor de bot separado: cada mensagem web ou IM recebida torna-se um turno normal do `ChatOrchestrator` dentro de um espaço de trabalho com âmbito de partner. Um partner é "um chat que tem personalidade e número de telefone."
<div align="center">
<img src="../../assets/figs/system/partners-architecture.png" alt="Arquitetura de partners DeepTutor" width="900">
</div>
Cada partner tem um `SOUL.md`, seleção de modelo, canais, política de ferramentas e biblioteca atribuída. As bases de conhecimento, skills e notebooks são copiadas para `data/partners/<id>/workspace/`, pelo que as mesmas ferramentas de RAG, skill, notebook e memória funcionam sem casos especiais. Um partner lê a memória do seu proprietário mas escreve apenas a sua própria.
<div align="center">
<img src="../../assets/figs/web-1.4.6+/partners/02-IM%20config%20for%20each%20partner.png" alt="Configuração de canal IM por partner" width="900">
</div>
A camada de canais é orientada por esquema e pode ligar-se a plataformas IM como Feishu, Telegram, Slack, Discord, DingTalk, QQ/NapCat, WeCom, WhatsApp, Zulip, Mattermost, Matrix, Mochat e Microsoft Teams dependendo dos extras instalados e das credenciais configuradas. Um partner também pode ser conectado como subagente e consultado a partir de um turno de chat normal — veja **Meus Agentes** abaixo.
</details>
<details>
<summary><b>🧑‍🚀 Meus Agentes — Consultar e Importar Outros Agentes</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/myagents/00-overview.png" alt="Espaço de trabalho Meus Agentes DeepTutor" width="900">
</div>
Meus Agentes transforma outros agentes em contexto para o DeepTutor, e faz duas coisas distintas. **Conectar um agente ao vivo** — um Claude Code ou Codex CLI na sua máquina, ou um dos seus Partners — e consultá-lo a partir de dentro de um turno de chat: o DeepTutor *executa* mesmo o outro agente e transmite o seu trabalho para o painel de Atividade via a ferramenta `consult_subagent`. Selecione-o com o chip de Agente (ou escreva `@`), e defina quantas rondas a consulta pode ter.
<div align="center">
<img src="../../assets/figs/web-1.4.6+/home/08-subagent%20demo%20with%20claude%20code.png" alt="Consultar um subagente Claude Code ao vivo" width="900">
</div>
**Importar conversas anteriores** — traga o seu histórico existente do Claude Code e Codex como agentes nomeados, pesquisáveis e retomáveis. Escolha quais os dias a importar; atualizar ressincroniza-os. Referencie uma conversa importada a partir de qualquer turno de chat via `+` → Meus Agentes, e o DeepTutor lê-a como uma transcrição de terceiros — permanece *a conversa deles*, não a voz própria do DeepTutor.
</details>
<details>
<summary><b>✍️ Co-Writer — Rascunho Markdown com Consciência de Seleção</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/co-writer/00-overview.png" alt="Espaço de trabalho Co-Writer DeepTutor" width="900">
</div>
Co-Writer é um espaço de trabalho Markdown de vista dividida para relatórios, tutoriais, notas e artefactos de aprendizagem de formato longo. Os documentos guardam automaticamente, renderizam uma pré-visualização em tempo real (matemática KaTeX, cercas de diagramas) e podem ser guardados de volta em notebooks quando um rascunho se torna contexto reutilizável.
<div align="center">
<img src="../../assets/figs/web-1.4.6+/co-writer/01-edit%20panel.png" alt="Editor Co-Writer com pré-visualização em tempo real" width="900">
</div>
A sua ideia central é a **edição cirúrgica**: selecione um trecho e peça ao DeepTutor para reescrever, expandir ou encurtar. O agente de edição pode fundamentar a alteração numa base de conhecimento ou evidência web, mantém um rasto das suas chamadas de ferramentas e mostra cada alteração como um diff aceitar/rejeitar — pelo que nada aterra até que aprove.
</details>
<details>
<summary><b>📖 Book (Livro) — Livros Vivos dos Seus Materiais</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/book/00-book_overview.png" alt="Biblioteca de livros DeepTutor" width="900">
</div>
Book converte fontes selecionadas num **livro vivo** interativo — não um PDF estático, mas um ambiente de leitura construído a partir de blocos tipados. Um livro pode começar a partir de bases de conhecimento, notebooks, bancos de perguntas ou histórico de chat; o fluxo de criação propõe uma estrutura de capítulos antes de o conteúdo ser gerado, para que os utilizadores possam rever a forma em vez de aceitar uma saída cega de disparo único.
<p align="center">
<img src="../../assets/figs/web-1.4.6+/book/01-book-demo-quiz%20card.png" alt="Bloco de quiz do Book" width="31%">
&nbsp;
<img src="../../assets/figs/web-1.4.6+/book/02-book-demo-manim%20video.png" alt="Bloco de animação Manim do Book" width="31%">
&nbsp;
<img src="../../assets/figs/web-1.4.6+/book/03-book-demo%20interactive%20module.png" alt="Bloco de widget interativo do Book" width="31%">
</p>
Cada capítulo compila em blocos tipados — texto, callouts, quizzes, cartões flash, linhas do tempo, código, figuras, HTML interativo, animações, gráficos de conceitos, mergulhos profundos e notas de utilizador — e cada página tem o seu próprio Page Chat. Os blocos são editáveis: inserir, mover, regenerar ou mudar o tipo de um bloco sem reescrever o capítulo. Os comandos de manutenção como `deeptutor book health` e `deeptutor book refresh-fingerprints` ajudam a detetar quando o conhecimento de origem divergiu das páginas compiladas.
</details>
<details>
<summary><b>📚 Centro de Conhecimento — Bibliotecas RAG Multi-Motor</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/knowledge/00-overview.png" alt="Centro de Conhecimento DeepTutor" width="900">
</div>
As bases de conhecimento são as coleções de documentos por trás do RAG — fundamentam os turnos do Chat, edições do Co-Writer, geração do Book e conversas do Partner. O que é distintivo é uma **escolha de motores de recuperação**: **LlamaIndex** (o padrão, vetor local + BM25), **PageIndex** (alojado, recuperação de raciocínio com citações ao nível da página), **GraphRAG** e **LightRAG** (recuperação de grafo de conhecimento), **LightRAG Server** (recuperação delegada a uma instância externa de LightRAG conectada via HTTP), ou um vault **Obsidian** vinculado que o tutor lê e escreve no lugar. Cada KB está vinculada a um motor.
<div align="center">
<img src="../../assets/figs/web-1.4.6+/knowledge/01-create%20knowledge%20base.png" alt="Criar uma base de conhecimento" width="900">
</div>
Ao criar uma KB, pode **criar nova** (carregar documentos e construir um índice novo) ou **vincular existente** (reutilizar um índice construído noutro lugar, ler no lugar sem reindexação). A reindexação escreve um novo diretório plano `version-N` e mantém os anteriores, pelo que um índice funcional nunca é destruído a meio de uma reconstrução. Um único documento pode ser removido mesmo de uma base em estado de **erro** — descartando um ficheiro que falhou a análise sem uma eliminação e reconstrução completas. A análise de documentos — Somente Texto, MinerU, Docling, markitdown ou PyMuPDF4LLM — é escolhida em **Settings → Knowledge Base**, com downloads de modelos locais desativados por predefinição. A CLI espelha o ciclo de vida com `deeptutor kb list`, `info`, `create`, `add`, `search`, `set-default` e `delete`.
</details>
<details>
<summary><b>🌐 Espaço de Aprendizado — Skills, Personas e Contexto Reutilizável</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/learning-space/00-overview.png" alt="Hub do Espaço de Aprendizado DeepTutor" width="900">
</div>
O Espaço de Aprendizado é a camada de biblioteca e personalização — onde vivem as coisas que persistem. **Conversas e Materiais** contém o seu histórico de chat, notebooks e um banco de questões (cada pergunta guardada mantém a sua resposta, a resposta de referência e uma explicação). **Personalização** contém caminhos de domínio, personas (predefinições de comportamento como *par*, *assistente de pesquisa*, *professor*) e skills (playbooks `SKILL.md` que o modelo lê a pedido). Tudo aqui pode ser reutilizado a partir do Chat, Partners, Co-Writer e Book.
<div align="center">
<img src="../../assets/figs/web-1.4.6+/learning-space/07-%20download%20skills%20from%20eduhub.png" alt="Importar skills do EduHub" width="900">
</div>
Não tem de escrever cada skill você mesmo — **Importar do EduHub** navega no catálogo da comunidade e descarrega uma skill diretamente para a sua biblioteca através de uma porta de segurança (veja [Ecossistema](#-ecossistema--eduhub-e-a-comunidade-de-skills)).
</details>
<details>
<summary><b>🧠 Memória — Personalização Inspecionável</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/memory/00-overview.png" alt="Visão geral da memória DeepTutor" width="900">
</div>
A Memória é um sistema de três camadas suportado por ficheiros que pode ler, curar e auditar — deliberadamente *não* um armazém de vetores oculto. **L1** é o espelho do espaço de trabalho mais um rasto de eventos append-only (`trace/<surface>/<date>.jsonl`); **L2** são factos curados por superfície (`L2/<surface>.md`); **L3** é a síntese entre superfícies (`L3/<profile|recent|scope|preferences>.md`). Como L2 cita L1 e L3 cita L2, nada no seu perfil é incontabilizável.
<div align="center">
<img src="../../assets/figs/web-1.4.6+/memory/01-3%20layer%20memory%20graph.png" alt="Gráfico de memória de três camadas DeepTutor" width="900">
</div>
O Memory Graph mostra toda a pirâmide — síntese L3 no centro, L2 no anel do meio, rastreamentos L1 no exterior — para que possa rastrear qualquer afirmação sintetizada até ao evento bruto exato que lhe deu origem. A memória é rastreada nas superfícies `chat`, `notebook`, `quiz`, `kb`, `book`, partner e `cowriter`; os orçamentos de Atualização / Auditoria / Deduplicação do consolidador são ajustados em **Settings → Memory**.
</details>
<details>
<summary><b>⚙️ Configurações — Um Plano de Controlo</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/settings/00-setting%20overview.png" alt="Hub de configurações DeepTutor" width="900">
</div>
Configurações é o plano de controlo operacional, com uma faixa de estado em tempo real (Backend, LLM, Embedding, Search) e um cartão por área: **Aparência** (tema + idioma da UI), **Rede** (base de API, portas, CORS), **Modelos** (LLM, Embedding, Search, Text-to-Speech, Speech-to-Text, Geração de Imagem, Geração de Vídeo), **Base de Conhecimento** (motor de análise de documentos), **Chat** (ferramentas, servidores MCP, parâmetros por capacidade), **Partners e Agentes** (os subagentes que pode consultar a partir de um turno) e **Memória** (os orçamentos do consolidador).
<div align="center">
<img src="../../assets/figs/web-1.4.6+/settings/01-appearance%20settings.png" alt="Configurações de aparência e temas DeepTutor" width="900">
</div>
A maioria das secções usa um fluxo de rascunho e aplicação, para que possa testar um provedor antes de o confirmar. Quatro temas incluídos — Default, Cream, Dark e Glass. Os ficheiros `.env` da raiz do projeto são intencionalmente ignorados; a configuração de runtime vive sob `data/user/settings/*.json` a menos que `DEEPTUTOR_HOME` ou `deeptutor start --home` aponte a aplicação para outro lugar.
</details>
<details>
<summary><b>👥 Multi-Utilizador — Implementações Partilhadas</b> · autenticação opcional, espaços de trabalho isolados por utilizador</summary>
A autenticação está **desativada por predefinição** — o DeepTutor corre em modo de utilizador único. Ative-a e uma árvore `data/` aloja um espaço de trabalho de administrador, espaços de trabalho por utilizador isolados e espaços de trabalho de partners lado a lado:
```text
data/
├── user/ # Espaço de trabalho de administrador + configurações globais
├── users/<uid>/ # Âmbito por utilizador: histórico de chat, memória, notebooks, KBs
├── partners/<id>/workspace/ # Âmbito de partner (utilizador sintético)
└── system/ # auth/users.json · grants/<uid>.json · audit/usage.jsonl
```
O **primeiro utilizador registado torna-se administrador** e possui catálogos de modelos, credenciais de provedores, bases de conhecimento partilhadas, skills e concessões por utilizador. Os restantes obtêm um espaço de trabalho isolado e uma página de Settings editada — modelos, KBs e skills atribuídos pelo administrador aparecem como opções com âmbito somente leitura, nunca como chaves API brutas.
**Ativar:** ligue a autenticação em `data/user/settings/auth.json`, reinicie `deeptutor start`, registe o primeiro administrador em `/register`, depois adicione utilizadores em `/admin/users` e atribua modelos, KBs, skills, Partners, política de ferramentas/MCP e acesso de execução de código através de concessões.
> O PocketBase continua a ser uma integração de utilizador único — mantenha `integrations.pocketbase_url` em branco para implementações multi-utilizador a menos que tenha ligado um armazém de utilizadores externo.
</details>
## ⌨️ DeepTutor CLI — Interface Nativa de Agentes
Um binário `deeptutor`, duas formas de entrada: um **REPL** interativo para pessoas que vivem no terminal, e **JSON** estruturado para outros agentes que conduzem o DeepTutor como uma ferramenta. As mesmas capacidades, ferramentas e bases de conhecimento de qualquer forma.
<details>
<summary><b>Conduzir você mesmo</b></summary>
`deeptutor chat` abre um REPL interativo; `deeptutor run <capability> "<message>"` dispara um único turno e sai. Ambos usam os mesmos flags `--capability`, `--tool`, `--kb` e `--config`.
```bash
deeptutor chat # REPL interativo
deeptutor chat --capability deep_solve --kb my-kb --tool rag
deeptutor run chat "Explain the Fourier transform" --tool rag --kb textbook
deeptutor run deep_research "Survey 2026 papers on RAG" \
--config mode=report --config depth=standard
```
Tudo o que a aplicação Web faz também está aqui — bases de conhecimento (`kb`), sessões (`session`), partners (`partner`), skills (`skill`), notebooks, memória e configuração. Lista completa abaixo.
</details>
<details>
<summary><b>Deixar um agente conduzir</b></summary>
O DeepTutor foi construído para ser *operado por outro agente*. Adicione `--format json` a qualquer `run` e cada turno transmite **NDJSON — um evento por linha** (`content`, `tool_call`, `tool_result`, `done`, …), cada linha marcada com o seu `session_id`. As execuções são seguras sem TTY: uma pausa `ask_user` sem TTY resolve-se automaticamente com uma resposta vazia em vez de bloquear.
```bash
# Disparo único, legível por máquina
deeptutor run deep_solve "Find d/dx[sin(x^2)]" --tool reason --format json
# Encadear turnos numa sessão com estado — capturar o id, reutilizá-lo
SID=$(deeptutor run deep_research "Survey 2026 papers on RAG" \
--config mode=report --config depth=standard --format json \
| jq -r 'select(.type=="done").session_id')
deeptutor run deep_question "Quiz me on that survey" --session "$SID" --format json
```
O repositório inclui um [`SKILL.md`](../../SKILL.md) raiz — um documento de transferência de ~150 linhas que ensina qualquer LLM com uso de ferramentas toda a superfície numa leitura. Passe-o ao Claude Code, Codex ou OpenCode (eles pegam no `SKILL.md` automaticamente), ou envolva `deeptutor run` como uma ferramenta num loop LangChain / AutoGen. Receitas completas: [Agent Handoff](https://deeptutor.info/docs/cli/agent-handoff/).
</details>
<details>
<summary><b>Referência de comandos</b></summary>
| Comando | Descrição |
|:---|:---|
| `deeptutor init` | Criar ou atualizar `data/user/settings` para o espaço de trabalho atual |
| `deeptutor start [--home PATH]` | Lançar backend + frontend juntos |
| `deeptutor serve [--port PORT]` | Iniciar apenas o backend FastAPI |
| `deeptutor run <capability> <message>` | Executar um turno de capacidade único (`chat`, `deep_solve`, `deep_question`, `deep_research`, `visualize`, `math_animator`, `mastery_path`); adicionar `--format json` para saída NDJSON |
| `deeptutor chat` | REPL interativo com controlos de capacidade, ferramenta, KB, notebook e histórico |
| `deeptutor partner list/create/start/stop` | Gerir partners ligados por IM |
| `deeptutor kb list/info/create/add/search/set-default/delete` | Gerir bases de conhecimento LlamaIndex |
| `deeptutor skill search/install/list/remove/login/logout/publish/update` | Gerir habilidades, instalar de hubs e publicar as suas (`eduhub:<slug>` por padrão, veja Ecossistema) |
| `deeptutor memory show/clear` | Inspecionar documentos de memória L2/L3 ou limpar memória L1/toda |
| `deeptutor session list/show/open/rename/delete` | Gerir sessões partilhadas |
| `deeptutor notebook list/create/show/add-md/replace-md/remove-record` | Gerir notebooks a partir de ficheiros Markdown |
| `deeptutor book list/health/refresh-fingerprints` | Inspecionar livros e atualizar impressões digitais de fontes |
| `deeptutor plugin list/info` | Inspecionar ferramentas e capacidades registadas |
| `deeptutor config show` | Imprimir resumo de configuração |
| `deeptutor provider login <provider>` | Autenticação de provedor (`openai-codex` login OAuth; `github-copilot` valida uma sessão de autenticação Copilot existente) |
</details>
<details>
<summary><b>Distribuição de apenas CLI</b></summary>
O pacote de apenas CLI encontra-se em `packaging/deeptutor-cli`. Neste checkout, instale-o a partir de fonte:
```bash
python -m pip install -e ./packaging/deeptutor-cli
```
Ainda não está publicado no PyPI, por isso a secção principal de [Começar](#-começar) mantém o caminho de instalação a partir de fonte.
</details>
## 🧩 Ecossistema — EduHub e a Comunidade de Skills
As skills do DeepTutor usam o formato aberto **Agent-Skills** — uma pasta com um playbook `SKILL.md` (frontmatter YAML + Markdown) e ficheiros de referência opcionais. Nada nisto é específico do DeepTutor, por isso qualquer registo que fale o formato torna-se uma fonte para a sua biblioteca. O DeepTutor inclui o **[EduHub](https://eduhub.deeptutor.info/)** — o nosso próprio registo de skills focado em educação — como hub padrão.
<details>
<summary><b>EduHub — o ecossistema de habilidades do DeepTutor</b></summary>
[**EduHub**](https://eduhub.deeptutor.info/) é o hub da comunidade que o DeepTutor lançou para partilhar skills de agentes orientadas para o ensino — tutores socráticos, construtores de cartões flash, feedback de redações, planos de exames, explicadores de conceitos e muito mais. Está integrado no DeepTutor, por isso não há nada a configurar: um slug simples ou um prefixo `eduhub:` resolve para ele.
**Encontrar e instalar** — no navegador, abra **Espaço de Aprendizado → Skills → Importar do EduHub** para navegar no catálogo e descarregar uma skill diretamente para a sua biblioteca. Do terminal:
```bash
deeptutor skill search "socratic tutor" # pesquisar EduHub (o hub padrão)
deeptutor skill install socratic-tutor # buscar → verificar → registar
deeptutor skill install eduhub:socratic-tutor@1.2.0 # fixar um hub e uma versão
deeptutor skill list # skills locais com a sua proveniência de hub
```
**Publicar a sua própria** — empacote um `SKILL.md` e partilhe-o de volta com a comunidade:
```bash
deeptutor skill login # login no navegador para o EduHub
deeptutor skill publish ./my-skill # interativo: escolher uma faixa + etiquetas, depois carregar
deeptutor skill update # reverter ou lançar uma nova versão
```
O EduHub também é um registo independente compatível com ClawHub, por isso agentes que não são o DeepTutor (Claude Code, Codex, …) podem usá-lo diretamente através da CLI `eduhub``npx eduhub install socratic-tutor`.
</details>
<details>
<summary><b>A porta de segurança de importação</b></summary>
Seja qual for a fonte, cada importação passa pela **mesma porta de segurança** antes de qualquer coisa tocar no seu espaço de trabalho:
- o **veredicto de segurança** do registo é verificado primeiro — os pacotes sinalizados são recusados a menos que passe `--allow-unverified`;
- os arquivos são extraídos defensivamente (proteções zip-slip / zip-bomb) atrás de uma **lista branca de sufixos** de texto/script, para que binários nunca aterrem no espaço de trabalho;
- o frontmatter é normalizado para o esquema do DeepTutor e `always:` é **removido**, por isso uma skill descarregada nunca pode forçar-se em cada prompt do sistema;
- a proveniência — hub, versão, veredicto e hora de instalação — é escrita em `.hub-lock.json` para auditorias e atualizações.
Em implementações multi-utilizador, instalar é exclusivo do administrador: uma nova skill aterra no catálogo do administrador e permanece invisível para outros utilizadores até que uma concessão a atribua, para que um administrador possa verificá-la antes de a implementar.
</details>
<details>
<summary><b>Também compatível com ClawHub</b></summary>
Como o DeepTutor fala o formato aberto Agent-Skills, o **[ClawHub](https://clawhub.ai/)** também funciona como fonte de primeira classe — está integrado juntamente com o EduHub. Escolha-o com o prefixo de hub:
```bash
deeptutor skill search "git release notes" --hub clawhub
deeptutor skill install clawhub:git-release-notes@1.0.1
```
Adicione mais registos em `settings/skill_hubs.json`: uma entrada `type: "clawhub"` aponta para qualquer API HTTP compatível (EduHub e ClawHub falam ambos), `type: "command"` envolve qualquer CLI de busca que um registo forneça, e `"default"` escolhe o hub usado para slugs simples. Todos eles alimentam a mesma porta de importação.
</details>
## 🌐 Comunidade
### 📮 Contacto
O DeepTutor é um projeto de código aberto liderado por [Bingxi Zhao](https://github.com/pancacake) dentro do Grupo [HKUDS](https://github.com/HKUDS), e itera numa **forma totalmente de código aberto**, construído em conjunto com a comunidade. Até agora, **NÃO** temos produtos online pagos de qualquer forma. Sinta-se à vontade para contactar em **bingxizhao39@gmail.com** para discussões, ideias ou colaboração.
### 🙏 Agradecimentos
Um agradecimento sincero a [**Chao Huang**](https://sites.google.com/view/chaoh), diretor do Data Intelligence Lab @ HKU, e aos nossos colegas do HKUDS pelo seu caloroso apoio — especialmente [**Jiahao Zhang**](https://github.com/zzhtx258), [**Zirui Guo**](https://github.com/LarFii) e [**Xubin Ren**](https://github.com/Re-bin). Também somos profundamente gratos à **comunidade de código aberto**: as suas estrelas, issues, pull requests e discussões moldam o DeepTutor todos os dias.
O DeepTutor também assenta nos ombros de projetos de código aberto excepcionais que nos deram tanto ferramentas como inspiração:
| Projeto | Papel / Inspiração |
|:---|:---|
| [**LlamaIndex**](https://github.com/run-llama/llama_index) | Espinha dorsal da pipeline RAG e indexação de documentos |
| [**nanobot**](https://github.com/HKUDS/nanobot) | Motor de agente ultraligeiro que alimentou o TutorBot original *(HKUDS)* |
| [**LightRAG**](https://github.com/HKUDS/LightRAG) | RAG Simples e Rápido *(HKUDS)* |
| [**AutoAgent**](https://github.com/HKUDS/AutoAgent) | Framework de Agentes Sem Código *(HKUDS)* |
| [**AI-Researcher**](https://github.com/HKUDS/AI-Researcher) | Pipeline de investigação automatizada *(HKUDS)* |
| [**OpenClaw**](https://github.com/openclaw/openclaw) | Gateway aberto de agentes e ecossistema de skills por trás do ClawHub |
| [**Codex**](https://github.com/openai/codex) | CLI de programação nativa de agentes que inspirou o nosso fluxo de trabalho CLI |
| [**Claude Code**](https://github.com/anthropics/claude-code) | CLI de programação agêntica que inspirou o loop de agente do DeepTutor |
| [**ManimCat**](https://github.com/Wing900/ManimCat) | Geração de animações matemáticas impulsionada por IA para o Math Animator |
### 🗺️ Roadmap & Contribuir
Queremos que o DeepTutor continue a iterar e a melhorar — e, em última análise, a tornar-se um presente que devolvemos à comunidade de código aberto. O nosso [**roadmap**](https://github.com/HKUDS/DeepTutor/issues/498) é atualizado continuamente; vote em itens lá ou proponha novos. Se quiser contribuir, veja o [**Guia de Contribuição**](../../CONTRIBUTING.md) para a estratégia de branches, padrões de código e como começar.
<div align="center">
Esperamos que o DeepTutor se torne um presente para a comunidade. 🎁
<a href="https://github.com/HKUDS/DeepTutor/graphs/contributors">
<img src="https://contrib.rocks/image?repo=HKUDS/DeepTutor&max=999" alt="Contribuidores" />
</a>
</div>
<div align="center">
<a href="https://www.star-history.com/#HKUDS/DeepTutor&type=timeline&legend=top-left">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=HKUDS/DeepTutor&type=timeline&theme=dark&legend=top-left" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=HKUDS/DeepTutor&type=timeline&legend=top-left" />
<img alt="Gráfico de histórico de estrelas" src="https://api.star-history.com/svg?repos=HKUDS/DeepTutor&type=timeline&legend=top-left" />
</picture>
</a>
</div>
<p align="center">
<a href="https://www.star-history.com/hkuds/deeptutor">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/badge?repo=HKUDS/DeepTutor&theme=dark" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/badge?repo=HKUDS/DeepTutor" />
<img alt="Classificação do histórico de estrelas" src="https://api.star-history.com/badge?repo=HKUDS/DeepTutor" />
</picture>
</a>
</p>
<div align="center">
Licenciado sob [Apache License 2.0](../../LICENSE).
<p>
<img src="https://visitor-badge.laobi.icu/badge?page_id=HKUDS.DeepTutor&style=for-the-badge&color=00d4ff" alt="Visualizações">
</p>
</div>
+707
View File
@@ -0,0 +1,707 @@
<div align="center">
<p align="center"><img src="../../assets/figs/logo/logo.png" alt="DeepTutor logo" height="56" style="vertical-align: middle;">&nbsp;<img src="../../assets/figs/logo/banner.png" alt="DeepTutor" height="48" style="vertical-align: middle;"></p>
# DeepTutor: Персонализированное Обучение на Базе Агентов
<p align="center">
<a href="https://deeptutor.info" target="_blank"><img alt="Docs — deeptutor.info" src="https://img.shields.io/badge/Docs-deeptutor.info%20%E2%86%97-0A0A0A?style=for-the-badge&labelColor=F5F5F4" height="36"></a>
</p>
<p align="center">
<a href="https://trendshift.io/repositories/17099?utm_source=repository-badge&amp;utm_medium=badge&amp;utm_campaign=badge-repository-17099" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/repositories/17099" alt="HKUDS%2FDeepTutor | Trendshift" width="250" height="55"/></a>&nbsp;
<a href="https://trendshift.io/repositories/17099?utm_source=trendshift-badge&amp;utm_medium=badge&amp;utm_campaign=badge-trendshift-17099" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/17099/daily" alt="HKUDS%2FDeepTutor | Trendshift" width="250" height="55"/></a>&nbsp;
<a href="https://trendshift.io/repositories/17099?utm_source=trendshift-badge&amp;utm_medium=badge&amp;utm_campaign=badge-trendshift-17099" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/17099/weekly?language=Python" alt="HKUDS%2FDeepTutor | Trendshift" width="250" height="55"/></a>
</p>
<p align="center">
<a href="../../README.md"><img alt="English" height="40" src="https://img.shields.io/badge/English-CDCFD4"></a>&nbsp;
<a href="README_CN.md"><img alt="简体中文" height="40" src="https://img.shields.io/badge/简体中文-CDCFD4"></a>&nbsp;
<a href="README_JA.md"><img alt="日本語" height="40" src="https://img.shields.io/badge/日本語-CDCFD4"></a>&nbsp;
<a href="README_ES.md"><img alt="Español" height="40" src="https://img.shields.io/badge/Español-CDCFD4"></a>&nbsp;
<a href="README_FR.md"><img alt="Français" height="40" src="https://img.shields.io/badge/Français-CDCFD4"></a>&nbsp;
<a href="README_AR.md"><img alt="Arabic" height="40" src="https://img.shields.io/badge/Arabic-CDCFD4"></a>&nbsp;
<a href="README_RU.md"><img alt="Русский" height="40" src="https://img.shields.io/badge/Русский-BCDCF7"></a>&nbsp;
<a href="README_HI.md"><img alt="Hindi" height="40" src="https://img.shields.io/badge/Hindi-CDCFD4"></a>&nbsp;
<a href="README_PT.md"><img alt="Português" height="40" src="https://img.shields.io/badge/Português-CDCFD4"></a>&nbsp;
<a href="README_TH.md"><img alt="Thai" height="40" src="https://img.shields.io/badge/Thai-CDCFD4"></a>&nbsp;
<a href="README_PL.md"><img alt="Polski" height="40" src="https://img.shields.io/badge/Polski-CDCFD4"></a>
</p>
[![Python 3.11+](https://img.shields.io/badge/Python-3.11%2B-3776AB?style=flat-square&logo=python&logoColor=white)](https://www.python.org/downloads/)
[![Next.js 16](https://img.shields.io/badge/Next.js-16-000000?style=flat-square&logo=next.js&logoColor=white)](https://nextjs.org/)
[![License](https://img.shields.io/badge/License-Apache_2.0-blue?style=flat-square)](LICENSE)
[![GitHub release](https://img.shields.io/github/v/release/HKUDS/DeepTutor?style=flat-square&color=brightgreen)](https://github.com/HKUDS/DeepTutor/releases)
[![arXiv](https://img.shields.io/badge/arXiv-2604.26962-b31b1b?style=flat-square&logo=arxiv&logoColor=white)](https://arxiv.org/abs/2604.26962)
[![Discord](https://img.shields.io/badge/Discord-Сообщество-5865F2?style=flat-square&logo=discord&logoColor=white)](https://discord.gg/eRsjPgMU4t)
[![Feishu](https://img.shields.io/badge/Feishu-Группа-00D4AA?style=flat-square&logo=feishu&logoColor=white)](./Communication.md)
[![WeChat](https://img.shields.io/badge/WeChat-Группа-07C160?style=flat-square&logo=wechat&logoColor=white)](https://github.com/HKUDS/DeepTutor/issues/78)
[Возможности](#-ключевые-возможности) · [Начать](#-начало-работы) · [Исследовать](#-обзор-deeptutor) · [CLI](#%EF%B8%8F-deeptutor-cli--интерфейс-для-агентов) · [Экосистема](#-экосистема--eduhub-и-сообщество-навыков) · [Сообщество](#-сообщество)
</div>
---
> 🤝 **Мы приветствуем любые вклады в проект!** Голосуйте за элементы дорожной карты или предлагайте новые на странице [`Roadmap`](https://github.com/HKUDS/DeepTutor/issues/498), а также изучите наше [Руководство по участию](CONTRIBUTING.md) с описанием стратегии ветвления, стандартов кодирования и инструкций по началу работы.
### 📰 Новости
- **2026-05-22** 🌐 Официальный сайт документации запущен на [**deeptutor.info**](https://deeptutor.info/) — руководства, справочники и туры по возможностям в одном месте.
- **2026-04-19** 🎉 20 тысяч звёзд за 111 дней! Благодарим за поддержку на пути к по-настоящему персонализированному интеллектуальному обучению.
- **2026-04-10** 📄 Наша статья опубликована на arXiv — прочитайте [препринт](https://arxiv.org/abs/2604.26962) о дизайне и идеях, лежащих в основе DeepTutor.
- **2026-02-06** 🚀 10 тысяч звёзд всего за 39 дней! Огромная благодарность нашему удивительному сообществу.
- **2026-01-01** 🎊 С Новым Годом! Присоединяйтесь к нашему [Discord](https://discord.gg/eRsjPgMU4t), [WeChat](https://github.com/HKUDS/DeepTutor/issues/78) или [Обсуждениям](https://github.com/HKUDS/DeepTutor/discussions) — давайте вместе формировать DeepTutor.
- **2025-12-29** 🎓 DeepTutor официально выпущен!
## ✨ Ключевые возможности
DeepTutor — это агентная учебная рабочая среда, объединяющая репетиторство, решение задач, генерацию викторин, исследования, визуализацию и практику освоения в одной расширяемой системе.
- **Единая среда выполнения для всех режимов** — Chat, Quiz, Research, Visualize, Solve и Mastery Path работают на одном цикле агента, поэтому вы переключаете цель, а не движок, и контекст перемещается вместе с учащимся.
- **Связанный контекст обучения** — базы знаний, книги, черновики Co-Writer, блокноты, банки вопросов, персоны и Memory доступны во всех рабочих процессах, а не живут в изолированных инструментах.
- **Субагенты и Partners** — консультируйте живой Claude Code, Codex или Partner из любого хода (или импортируйте их прошлые разговоры) и запускайте постоянных IM-компаньонов на том же мозге.
- **Многодвигательные знания** — версионированные RAG-библиотеки на основе LlamaIndex, PageIndex, GraphRAG, LightRAG или связанного хранилища Obsidian с подключаемым разбором документов.
- **Расширяемые инструменты и навыки** — встроенные инструменты, MCP-серверы, модели генерации изображений / видео / голоса и устанавливаемые навыки сообщества из EduHub.
- **Проверяемая память** — трассировки L1, сводки поверхностей L2 и синтез L3 делают персонализацию видимой и редактируемой, а Memory Graph прослеживает каждое утверждение до его источника.
---
## 🚀 Начало работы
DeepTutor поставляется с четырьмя путями установки. Все они используют одну структуру рабочего пространства: настройки хранятся в `data/user/settings/` в директории запуска (или в `DEEPTUTOR_HOME` / `deeptutor start --home`, если задано явно). Для полного приложения рекомендуемый процесс: **выбрать директорию рабочего пространства → установить → `deeptutor init` → `deeptutor start`**.
<details>
<summary><b>Вариант 1 — Установка из PyPI</b> · полное локальное веб-приложение + CLI, клонирование не требуется</summary>
Полное локальное веб-приложение + CLI без необходимости клонирования. Требуется **Python 3.11+** и среда выполнения **Node.js 20+** в PATH (упакованный автономный сервер Next.js запускается командой `deeptutor start`).
```bash
mkdir -p my-deeptutor && cd my-deeptutor
pip install -U deeptutor
deeptutor init # запрашивает порты + провайдер LLM + необязательное встраивание
deeptutor start # запускает бэкенд + фронтенд; держите терминал открытым
```
`deeptutor init` запрашивает порт бэкенда (по умолчанию `8001`), порт фронтенда (по умолчанию `3782`), провайдер LLM / базовый URL / API-ключ / модель и необязательный провайдер встраивания для базы знаний / RAG.
После `deeptutor start` откройте URL фронтенда, напечатанный в терминале — по умолчанию [http://127.0.0.1:3782](http://127.0.0.1:3782). Нажмите `Ctrl+C` в этом терминале, чтобы остановить бэкенд и фронтенд. Пропустить `deeptutor init` можно для быстрого пробного запуска; приложение загружается с портами по умолчанию и пустыми настройками модели, которые можно настроить позже в **Настройки → Модели**.
</details>
<details>
<summary><b>Вариант 2 — Установка из исходного кода</b> · разработка на основе чекаута</summary>
Для разработки на основе чекаута. Используйте **Python 3.11+** и **Node.js 22 LTS** для соответствия CI и Docker.
```bash
git clone https://github.com/HKUDS/DeepTutor.git
cd DeepTutor
# Создание venv (macOS/Linux). Windows PowerShell:
# py -3.11 -m venv .venv ; .\.venv\Scripts\Activate.ps1
python3 -m venv .venv && source .venv/bin/activate
python -m pip install --upgrade pip
# Установка зависимостей бэкенда + фронтенда
python -m pip install -e .
( cd web && npm ci --legacy-peer-deps )
deeptutor init
deeptutor start
```
Установки из исходного кода запускают Next.js в режиме разработки для локальной директории `web/`; всё остальное (структура конфигурации, порты, остановка с `Ctrl+C`) соответствует Варианту 1.
<details>
<summary><b>Среда Conda</b> (вместо <code>venv</code>)</summary>
```bash
conda create -n deeptutor python=3.11
conda activate deeptutor
python -m pip install --upgrade pip
```
</details>
<details>
<summary><b>Необязательные дополнения при установке</b> — dev / partners / matrix / math-animator</summary>
```bash
pip install -e ".[dev]" # инструменты тестирования/линтинга
pip install -e ".[partners]" # SDK каналов IM для Партнёров + MCP-клиент
pip install -e ".[matrix]" # канал Matrix без E2EE/libolm
pip install -e ".[matrix-e2e]" # Matrix E2EE; требует libolm
pip install -e ".[math-animator]" # дополнение Manim; требует LaTeX/ffmpeg/системных библиотек
```
</details>
<details>
<summary><b>Настройка зависимостей фронтенда и устранение неполадок сервера разработки</b></summary>
**Изменение зависимостей фронтенда:** запустите `npm install --legacy-peer-deps` для обновления `web/package-lock.json`, затем зафиксируйте оба файла `web/package.json` и `web/package-lock.json`.
**Зависший сервер разработки:** если `deeptutor start` сообщает о существующем фронтенде, который не отвечает, остановите PID, который он печатает. Если процесс Next.js фактически не запущен, файлы блокировки устарели — удалите их и повторите попытку:
```bash
rm -f web/.next/dev/lock web/.next/lock
deeptutor start
```
</details>
</details>
<details>
<summary><b>Вариант 3 — Docker</b> · один автономный контейнер</summary>
Один контейнер для полного веб-приложения. Образы в GitHub Container Registry:
- `ghcr.io/hkuds/deeptutor:latest` — стабильный выпуск
- `ghcr.io/hkuds/deeptutor:pre` — предварительный выпуск, когда доступен
> Смотрите [CONTAINERIZATION.md](./CONTAINERIZATION.md) для развёртываний на podman/rootless/read-only-rootfs и полного руководства по установке.
```bash
docker run --rm --name deeptutor \
-p 127.0.0.1:3782:3782 \
-v deeptutor-data:/app/data \
ghcr.io/hkuds/deeptutor:latest
```
> **Публиковать нужно только порт `3782`.** Браузер обращается исключительно к источнику фронтенда; промежуточный слой Next.js (`web/proxy.ts`) перенаправляет `/api/*` и `/ws/*` на бэкенд FastAPI **внутри контейнера**. Публикация `8001` (`-p 127.0.0.1:8001:8001`) необязательна — полезна только при прямом обращении к API через curl или скрипты.
Откройте [http://127.0.0.1:3782](http://127.0.0.1:3782). Контейнер создаёт `/app/data/user/settings/*.json` при первом запуске; настройте провайдеров моделей на странице веб-настроек. Конфигурация, API-ключи, логи, файлы рабочего пространства, память и базы знаний сохраняются в томе `deeptutor-data`.
- **Другие порты хоста:** измените левую часть каждого маппинга `-p host:container` (например, `-p 127.0.0.1:8088:3782`). Если вы измените порты на стороне контейнера в `/app/data/user/settings/system.json`, перезапустите и обновите правую часть каждого маппинга.
- **Фоновый режим:** добавьте `-d`, затем `docker logs -f deeptutor` для слежения, `docker stop deeptutor` для остановки, `docker rm deeptutor` перед повторным использованием имени. Том `deeptutor-data` сохраняет ваши настройки и рабочее пространство между перезапусками.
**Удалённый Docker / обратный прокси:** браузер обращается только к источнику фронтенда (`:3782`); промежуточный слой Next.js внутри контейнера перенаправляет `/api/*` и `/ws/*` на бэкенд на стороне сервера. В типичном случае с одним контейнером вы вообще не настраиваете базовый URL API — просто направьте ваш обратный прокси / TLS-терминатор на `:3782`. Базовый URL API нужен только для **разделённого развёртывания** (бэкенд в отдельном контейнере/хосте): установите `next_public_api_base` в `data/user/settings/system.json` на внутрисетевой адрес, который фронтенд-сервер использует для достижения бэкенда (он читается на стороне сервера, никогда не отправляется браузеру).
```json
{
"next_public_api_base": "http://backend:8001"
}
```
`next_public_api_base_external` (и его псевдоним `public_api_base`) принимаются как запасные варианты с более низким приоритетом. CORS использует **источники** фронтенда, а не URL API. При отключённой аутентификации DeepTutor разрешает обычные HTTP/HTTPS источники браузера по умолчанию. При включённой аутентификации добавьте точные источники фронтенда:
```json
{
"cors_origins": ["https://deeptutor.example.com"]
}
```
<details>
<summary><b>Подключение к Ollama / LM Studio / llama.cpp / vLLM / Lemonade на хосте</b></summary>
Внутри Docker `localhost` — это сам контейнер, а не хост-машина. Чтобы обратиться к модельному сервису, запущенному на хосте, используйте шлюз хоста (рекомендуется):
```bash
docker run --rm --name deeptutor \
-p 127.0.0.1:3782:3782 -p 127.0.0.1:8001:8001 \
--add-host=host.docker.internal:host-gateway \
-v deeptutor-data:/app/data \
ghcr.io/hkuds/deeptutor:latest
```
Затем в **Настройки → Модели** укажите базовый URL провайдера как `host.docker.internal`:
- Ollama LLM: `http://host.docker.internal:11434/v1`
- Ollama embedding: `http://host.docker.internal:11434/api/embed`
- LM Studio: `http://host.docker.internal:1234/v1`
- llama.cpp: `http://host.docker.internal:8080/v1`
- Lemonade: `http://host.docker.internal:13305/api/v1`
Docker Desktop (macOS/Windows) обычно разрешает `host.docker.internal` без `--add-host`. На Linux этот флаг — переносимый способ создания этого имени хоста в современном Docker Engine.
**Альтернатива для Linux — сетевой режим хоста:** добавьте `--network=host` и уберите флаги `-p`. Контейнер напрямую использует сеть хоста, поэтому откройте [http://127.0.0.1:3782](http://127.0.0.1:3782) (или `frontend_port` в `system.json`), а сервисы хоста доступны через обычные localhost-URL, например `http://127.0.0.1:11434/v1`. Обратите внимание, что хостовый сетевой режим открывает порты контейнера напрямую на хосте и может конфликтовать с существующими сервисами — чтобы оставить их на loopback, установите `BACKEND_HOST=127.0.0.1` и `FRONTEND_HOST=127.0.0.1` (см. [CONTAINERIZATION.md](./CONTAINERIZATION.md)).
</details>
</details>
<details>
<summary><b>Вариант 4 — Только CLI</b> · без веб-интерфейса, из чекаута исходного кода</summary>
Когда веб-интерфейс не нужен. Пакет только для CLI устанавливается из чекаута исходного кода, а не из PyPI.
```bash
git clone https://github.com/HKUDS/DeepTutor.git
cd DeepTutor
# Создание venv (macOS/Linux). Windows PowerShell:
# py -3.11 -m venv .venv-cli ; .\.venv-cli\Scripts\Activate.ps1
python3 -m venv .venv-cli && source .venv-cli/bin/activate
python -m pip install --upgrade pip
python -m pip install -e ./packaging/deeptutor-cli
deeptutor init --cli
deeptutor chat
```
`deeptutor init --cli` использует ту же структуру `data/user/settings/`, что и полное приложение, но пропускает запросы портов бэкенда/фронтенда и по умолчанию отключает встраивание (выберите `Yes`, если планируете использовать `deeptutor kb …` или инструменты RAG). Он всё равно записывает полную структуру среды выполнения (`system.json`, `auth.json`, `integrations.json`, `model_catalog.json`, `main.yaml`, `agents.yaml`) и запрашивает активный провайдер и модель LLM.
<details>
<summary><b>Основные команды</b></summary>
```bash
deeptutor chat # интерактивный REPL
deeptutor chat --capability deep_solve --tool rag --kb my-kb
deeptutor run chat "Explain Fourier transform"
deeptutor run deep_solve "Solve x^2 = 4" --tool rag --kb my-kb
deeptutor kb create my-kb --doc textbook.pdf
deeptutor memory show
deeptutor config show
```
</details>
Локальная установка `deeptutor-cli` не включает веб-ресурсы или серверные зависимости. Сохраните чекаут исходного кода — редактируемая установка указывает на него. Чтобы позже добавить веб-приложение, установите пакет PyPI (Вариант 1) и запустите `deeptutor init` + `deeptutor start` из того же рабочего пространства.
</details>
<details>
<summary><b>Песочница выполнения кода (офисные навыки)</b> · запуск сгенерированного моделью кода для docx / pdf / pptx / xlsx</summary>
Встроенные офисные навыки — **docx / pdf / pptx / xlsx** — работают, заставляя модель написать короткий Python-скрипт (`python-docx`, `reportlab`, `openpyxl`, …), запустить его через инструменты `exec` / `code_execution` и вернуть URL для скачивания. Эти инструменты монтируются при наличии активного бэкенда песочницы, который активен **по умолчанию** в каждом варианте развёртывания:
- **Локально (Вариант 1 / 2) и Docker (Вариант 3, один контейнер):** ограниченная подпроцессная песочница запускает код модели (локально на хосте или внутри контейнера под Docker — контейнер сам является изолирующей границей).
- **docker-compose:** вместо этого направляется в защищённый сайдкар с минимальными привилегиями (**runner sidecar** `Dockerfile.runner`) через `DEEPTUTOR_SANDBOX_RUNNER_URL` — наиболее строгий вариант, используемый автоматически при наличии.
Подпроцессная песочница управляется настройкой `sandbox_allow_subprocess` в `data/user/settings/system.json` (по умолчанию `true`). Запуск сгенерированного моделью кода на вашем хосте — это реальное доверительное решение; установите значение `false` (или экспортируйте `DEEPTUTOR_SANDBOX_ALLOW_SUBPROCESS=0`) для отключения выполнения на стороне хоста, ценой того, что офисные навыки больше не смогут создавать файлы.
</details>
<details>
<summary><b>Справочник конфигурации</b> — файлы конфигурации в <code>data/user/settings/</code> (JSON/YAML)</summary>
Всё в `data/user/settings/` — это обычный JSON/YAML. Страница **Настройки** в браузере является рекомендуемым редактором.
| Файл | Назначение |
|:---|:---|
| `model_catalog.json` | Профили провайдеров LLM, встраивания и поиска; API-ключи; активные модели |
| `system.json` | Порты бэкенда/фронтенда, публичный базовый URL API, CORS, верификация SSL, директория вложений |
| `auth.json` | Необязательное переключение аутентификации, имя пользователя, хэш пароля, настройки токенов/куки |
| `integrations.json` | Необязательные настройки интеграции PocketBase и сайдкара |
| `interface.json` | Язык интерфейса / тема / настройки боковой панели |
| `main.yaml` | Значения по умолчанию для среды выполнения и внедрение пути |
| `agents.yaml` | Настройки температуры и токенов для возможностей/инструментов |
Корневой файл `.env` проекта **не** читается как файл конфигурации приложения. Для минимальной настройки модели откройте **Настройки → Модели**, добавьте профиль LLM (базовый URL / API-ключ / имя модели) и сохраните. Добавляйте профиль встраивания только если планируете использовать функции базы знаний / RAG.
</details>
## 📖 Обзор DeepTutor
Начните с основных поверхностей, которые вы будете использовать ежедневно: Chat, Partners, My Agents, Co-Writer, Book, Knowledge Center, Learning Space, Memory и Settings. Затем тур охватывает многопользовательские развёртывания для общих изолированных рабочих пространств.
<div align="center">
<img src="../../assets/figs/web-1.4.6+/OVERVIEW.png" alt="Главная страница DeepTutor — рабочее пространство чата со всеми поверхностями на боковой панели" width="900">
</div>
<details>
<summary><b>🏗️ Архитектура системы</b></summary>
<div align="center">
<img src="../../assets/figs/system/system%20architecture.png" alt="Архитектура системы DeepTutor" width="900">
</div>
</details>
<details>
<summary><b>💬 Чат — Цикл Агента, Который Вы Используете на Практике</b></summary>
Чат — это возможность по умолчанию и место, где начинается большинство работ. Один поток может нормально общаться, вызывать инструменты, опираться на выбранные базы знаний, читать вложения, генерировать изображения, обращаться к субагентам, записывать в блокнот и продолжать с тем же контекстом в последующих ходах.
<div align="center">
<img src="../../assets/figs/web-1.4.6+/home/00-overview.png" alt="Рабочее пространство чата DeepTutor" width="900">
</div>
Цикл намеренно прост: модель думает раундами, вызывает инструменты при необходимости, наблюдает результаты и завершает сообщением без инструментов. `ask_user` особенный — вместо угадывания агент может приостановить ход, задать структурированный уточняющий вопрос и возобновить работу, когда вы ответите.
<div align="center">
<img src="../../assets/figs/system/chat-agent-loop.png" alt="Цикл агента чата DeepTutor" width="900">
</div>
Переключаемые пользователем инструменты: `brainstorm`, `web_search`, `paper_search`, `reason` и `geogebra_analysis` — плюс `imagegen` и `videogen` после настройки соответствующей генеративной модели. Контекстные инструменты, такие как `rag`, `read_source`, `read_memory`, `write_memory`, `read_skill`, `load_tools`, `exec`, `web_fetch`, `ask_user`, `list_notebook`, `write_note`, `github` и `consult_subagent`, монтируются автоматически, когда ход имеет подходящий контекст.
Контекст бывает двух видов: **постоянный контекст сессии** (субагент, базы знаний, персонаж, модель, голос) находится на панели инструментов редактора и сохраняется между ходами; **одноразовые ссылки** (файлы, история чата, книги, блокноты, банк вопросов, импортированные агенты) берутся из меню `+` для одного хода.
Чат также является точкой запуска более глубоких возможностей: **Quiz** для генерации вопросов, **Research** для цитируемых отчётов, **Visualize** для графиков / диаграмм / анимаций, и — в разделе *Дополнительные возможности***Solve** для обоснованных рассуждений и **Mastery Path** для учебных планов.
</details>
<details>
<summary><b>🤝 Partner — Постоянные Компаньоны на Том Же Мозге</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/partners/00-partners%20overview.png" alt="Рабочее пространство партнёров DeepTutor" width="900">
</div>
Партнёры — это постоянные компаньоны со своей душой, политикой модели, библиотекой, памятью и каналами. Они не являются отдельным движком бота: каждое входящее веб- или IM-сообщение становится обычным ходом `ChatOrchestrator` внутри рабочего пространства, ограниченного партнёром. Партнёр — это «чат с личностью и номером телефона».
<div align="center">
<img src="../../assets/figs/system/partners-architecture.png" alt="Архитектура партнёров DeepTutor" width="900">
</div>
Каждый партнёр имеет `SOUL.md`, выбор модели, каналы, политику инструментов и назначенную библиотеку. Базы знаний, навыки и блокноты копируются в `data/partners/<id>/workspace/`, поэтому те же инструменты RAG, навыков, блокнотов и памяти работают без специальных случаев. Партнёр читает память своего владельца, но пишет только в собственную.
<div align="center">
<img src="../../assets/figs/web-1.4.6+/partners/02-IM%20config%20for%20each%20partner.png" alt="Конфигурация IM-канала для каждого партнёра" width="900">
</div>
Слой каналов управляется схемой и может подключаться к IM-платформам, таким как Feishu, Telegram, Slack, Discord, DingTalk, QQ/NapCat, WeCom, WhatsApp, Zulip, Mattermost, Matrix, Mochat и Microsoft Teams, в зависимости от установленных дополнений и настроенных учётных данных. Партнёр также может быть подключён как субагент и использован из обычного хода чата — см. **Мои Агенты** ниже.
</details>
<details>
<summary><b>🧑‍🚀 Мои Агенты — Консультация и Импорт Других Агентов</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/myagents/00-overview.png" alt="Рабочее пространство «Мои Агенты» DeepTutor" width="900">
</div>
Мои Агенты превращают других агентов в контекст для DeepTutor и делают две разные вещи. **Подключите живого агента** — Claude Code или Codex CLI на вашей машине, или одного из ваших Партнёров — и обращайтесь к нему изнутри хода чата: DeepTutor фактически *запускает* другого агента и транслирует его работу в панель Activity через инструмент `consult_subagent`. Выберите его чипом агента (или введите `@`) и задайте, сколько раундов может занять обращение.
<div align="center">
<img src="../../assets/figs/web-1.4.6+/home/08-subagent%20demo%20with%20claude%20code.png" alt="Обращение к субагенту Claude Code в реальном времени" width="900">
</div>
**Импортируйте прошлые разговоры** — загрузите существующую историю Claude Code и Codex как именованных, доступных для поиска, возобновляемых агентов. Выберите, за какие дни импортировать; обновление повторно синхронизирует их. Ссылайтесь на импортированный разговор из любого хода чата через `+` → Мои Агенты, и DeepTutor читает его как транскрипт третьей стороны — это *их* разговор, а не собственный голос DeepTutor.
</details>
<details>
<summary><b>✍️ Co-Writer — Редактирование Markdown с Учётом Выделения</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/co-writer/00-overview.png" alt="Рабочее пространство Co-Writer DeepTutor" width="900">
</div>
Co-Writer — это разделённое рабочее пространство Markdown для отчётов, руководств, заметок и долгосрочных учебных артефактов. Документы автосохраняются и отображают живой предварительный просмотр (математика KaTeX, ограждения диаграмм), и могут быть сохранены обратно в блокноты, когда черновик становится повторно используемым контекстом.
<div align="center">
<img src="../../assets/figs/web-1.4.6+/co-writer/01-edit%20panel.png" alt="Редактор Co-Writer с живым предварительным просмотром" width="900">
</div>
Его определяющая идея — **хирургическое редактирование**: выберите фрагмент и попросите DeepTutor переписать, расширить или сократить его. Агент редактирования может опираться на базу знаний или веб-данные, ведёт след вызовов инструментов и показывает каждое изменение как diff с принятием/отклонением — так ничто не применяется до вашего одобрения.
</details>
<details>
<summary><b>📖 Книга — Живые Книги из Ваших Материалов</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/book/00-book_overview.png" alt="Библиотека книг DeepTutor" width="900">
</div>
Книга превращает выбранные источники в интерактивную **живую книгу** — не статический PDF, а среда чтения, построенная из типизированных блоков. Книга может начинаться с баз знаний, блокнотов, банков вопросов или истории чата; процесс создания предлагает план глав перед генерацией содержания, поэтому вы рассматриваете структуру вместо того, чтобы принимать слепой одноразовый вывод.
<p align="center">
<img src="../../assets/figs/web-1.4.6+/book/01-book-demo-quiz%20card.png" alt="Блок викторины книги" width="31%">
&nbsp;
<img src="../../assets/figs/web-1.4.6+/book/02-book-demo-manim%20video.png" alt="Блок анимации Manim книги" width="31%">
&nbsp;
<img src="../../assets/figs/web-1.4.6+/book/03-book-demo%20interactive%20module.png" alt="Блок интерактивного виджета книги" width="31%">
</p>
Каждая глава компилируется в типизированные блоки — текст, выноски, викторины, флэш-карточки, временные шкалы, код, рисунки, интерактивный HTML, анимации, концептуальные графы, углублённые рассуждения и пользовательские заметки — и каждая страница имеет свой собственный чат. Блоки редактируемы: вставляйте, перемещайте, регенерируйте или меняйте тип блока без переписывания главы. Команды обслуживания `deeptutor book health` и `deeptutor book refresh-fingerprints` помогают обнаружить, когда исходные знания расходятся со скомпилированными страницами.
</details>
<details>
<summary><b>📚 Центр Знаний — Многодвигательные RAG-Библиотеки</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/knowledge/00-overview.png" alt="Центр Знаний DeepTutor" width="900">
</div>
Базы знаний — это коллекции документов для RAG, которые обосновывают ходы Chat, редакции Co-Writer, генерацию Book и разговоры с Партнёрами. Отличительной чертой является **выбор движков поиска**: **LlamaIndex** (по умолчанию, локальный вектор + BM25), **PageIndex** (размещённый, поиск с рассуждением с цитатами на уровне страницы), **GraphRAG** и **LightRAG** (поиск на основе графа знаний), **LightRAG Server** (поиск, делегированный внешнему экземпляру LightRAG, подключаемому по HTTP), или связанное хранилище **Obsidian**, которое репетитор читает и записывает на месте. Каждая KB привязана к одному движку.
<div align="center">
<img src="../../assets/figs/web-1.4.6+/knowledge/01-create%20knowledge%20base.png" alt="Создание базы знаний" width="900">
</div>
При создании KB вы либо **создаёте новую** (загружаете документы и строите свежий индекс), либо **связываете существующую** (повторно используете индекс, построенный в другом месте, читаете на месте без переиндексирования). Переиндексирование записывает новую плоскую директорию `version-N` и сохраняет предыдущие, поэтому рабочий индекс никогда не уничтожается в процессе перестройки. Отдельный документ можно удалить даже из базы в состоянии **error** — убрав файл, который не удалось разобрать, без полного удаления и пересборки. Разбор документов — только текст, MinerU, Docling, markitdown или PyMuPDF4LLM — выбирается в **Настройки → База знаний**, с отключёнными по умолчанию загрузками локальных моделей. CLI отражает жизненный цикл командами `deeptutor kb list`, `info`, `create`, `add`, `search`, `set-default` и `delete`.
</details>
<details>
<summary><b>🌐 Пространство Обучения — Навыки, Персоны и Многоразовый Контекст</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/learning-space/00-overview.png" alt="Хаб Пространства Обучения DeepTutor" width="900">
</div>
Пространство Обучения — это библиотека и уровень персонализации — место, где живут постоянные вещи. **Разговоры и материалы** содержат историю чата, блокноты и банк вопросов (каждый сохранённый вопрос хранит ваш ответ, эталонный ответ и объяснение). **Персонализация** содержит пути мастерства, персонажей (поведенческие пресеты, такие как *коллега*, *исследовательский ассистент*, *учитель*) и навыки (сценарии `SKILL.md`, которые модель читает по требованию). Всё здесь можно повторно использовать из Chat, Partners, Co-Writer и Book.
<div align="center">
<img src="../../assets/figs/web-1.4.6+/learning-space/07-%20download%20skills%20from%20eduhub.png" alt="Импорт навыков из EduHub" width="900">
</div>
Вам не нужно писать каждый навык самостоятельно — **Импорт из EduHub** просматривает каталог сообщества и загружает навык прямо в вашу библиотеку через шлюз безопасности (см. [Экосистема](#-экосистема--eduhub-и-сообщество-навыков)).
</details>
<details>
<summary><b>🧠 Память — Проверяемая Персонализация</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/memory/00-overview.png" alt="Обзор Памяти DeepTutor" width="900">
</div>
Память — это трёхуровневая система на основе файлов, которую можно читать, курировать и проверять — намеренно *не* скрытое векторное хранилище. **L1** — зеркало рабочего пространства плюс трассировка событий только для добавления (`trace/<surface>/<date>.jsonl`); **L2** — курированные факты на уровне поверхности (`L2/<surface>.md`); **L3** — межповерхностный синтез (`L3/<profile|recent|scope|preferences>.md`). Поскольку L2 цитирует L1, а L3 цитирует L2, ничто в вашем профиле не является неотчётным.
<div align="center">
<img src="../../assets/figs/web-1.4.6+/memory/01-3%20layer%20memory%20graph.png" alt="Граф Памяти DeepTutor" width="900">
</div>
Граф памяти показывает всю пирамиду — синтез L3 в центре, L2 в среднем кольце, трассировки L1 снаружи — так что вы можете проследить любое синтезированное утверждение обратно до точного исходного события. Память отслеживается по поверхностям `chat`, `notebook`, `quiz`, `kb`, `book`, partner и `cowriter`; бюджеты обновления / аудита / дедупликации консолидатора настраиваются в **Настройки → Память**.
</details>
<details>
<summary><b>⚙️ Настройки — Единая Панель Управления</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/settings/00-setting%20overview.png" alt="Хаб настроек DeepTutor" width="900">
</div>
Настройки — это операционная панель управления с живой строкой статуса (Бэкенд, LLM, Встраивание, Поиск) и одной карточкой для каждой области: **Внешний вид** (тема + язык интерфейса), **Сеть** (базовый URL API, порты, CORS), **Модели** (LLM, Встраивание, Поиск, Синтез речи, Распознавание речи, Генерация изображений, Генерация видео), **База знаний** (движок разбора документов), **Чат** (инструменты, MCP-серверы, параметры по возможностям), **Партнёры и агенты** (субагенты, к которым можно обратиться из хода) и **Память** (бюджеты консолидатора).
<div align="center">
<img src="../../assets/figs/web-1.4.6+/settings/01-appearance%20settings.png" alt="Настройки внешнего вида и темы DeepTutor" width="900">
</div>
Большинство разделов используют поток черновика и применения, поэтому вы можете протестировать провайдера перед подтверждением. В комплект входят четыре темы — Default, Cream, Dark и Glass. Корневые файлы `.env` проекта намеренно игнорируются; конфигурация среды выполнения хранится в `data/user/settings/*.json`, если только `DEEPTUTOR_HOME` или `deeptutor start --home` не указывает приложению другое место.
</details>
<details>
<summary><b>👥 Многопользовательский режим — Общие Развёртывания</b> · необязательная аутентификация, изолированные рабочие пространства</summary>
Аутентификация **отключена по умолчанию** — DeepTutor работает в однопользовательском режиме. Включите её, и одно дерево `data/` содержит рабочее пространство администратора, изолированные пользовательские рабочие пространства и партнёрские рабочие пространства рядом:
```text
data/
├── user/ # Рабочее пространство администратора + глобальные настройки
├── users/<uid>/ # Пользовательская область: история чата, память, блокноты, KB
├── partners/<id>/workspace/ # Область партнёра (синтетического пользователя)
└── system/ # auth/users.json · grants/<uid>.json · audit/usage.jsonl
```
**Первый зарегистрированный пользователь становится администратором** и владеет каталогами моделей, учётными данными провайдеров, общими базами знаний, навыками и грантами для пользователей. Все остальные получают изолированное рабочее пространство и отредактированную страницу Настроек — назначенные администратором модели, KB и навыки отображаются как ограниченные опции только для чтения, а не как сырые API-ключи.
**Включение:** включите аутентификацию в `data/user/settings/auth.json`, перезапустите `deeptutor start`, зарегистрируйте первого администратора по адресу `/register`, затем добавляйте пользователей из `/admin/users` и назначайте модели, KB, навыки, Partners, политику инструментов/MCP и доступ к выполнению кода через гранты.
> PocketBase остаётся однопользовательской интеграцией — оставьте `integrations.pocketbase_url` пустым для многопользовательских развёртываний, если только вы не подключили внешнее хранилище пользователей.
</details>
## ⌨️ DeepTutor CLI — Интерфейс для Агентов
Один бинарный файл `deeptutor`, два способа входа: интерактивный **REPL** для тех, кто живёт в терминале, и структурированный **JSON** для других агентов, которые управляют DeepTutor как инструментом. Одни и те же возможности, инструменты и базы знаний в любом случае.
<details>
<summary><b>Управляйте им самостоятельно</b></summary>
`deeptutor chat` открывает интерактивный REPL; `deeptutor run <capability> "<message>"` выполняет один ход и завершается. Оба используют одинаковые флаги `--capability`, `--tool`, `--kb` и `--config`.
```bash
deeptutor chat # интерактивный REPL
deeptutor chat --capability deep_solve --kb my-kb --tool rag
deeptutor run chat "Explain the Fourier transform" --tool rag --kb textbook
deeptutor run deep_research "Survey 2026 papers on RAG" \
--config mode=report --config depth=standard
```
Всё, что делает веб-приложение, доступно и здесь — базы знаний (`kb`), сессии (`session`), партнёры (`partner`), навыки (`skill`), блокноты, память и конфигурация. Полный список ниже.
</details>
<details>
<summary><b>Позвольте агенту управлять им</b></summary>
DeepTutor создан для того, чтобы *им управлял другой агент*. Добавьте `--format json` к любой команде `run`, и каждый ход транслирует **NDJSON — одно событие на строку** (`content`, `tool_call`, `tool_result`, `done`, …), каждая строка помечена своим `session_id`. Запуски безопасны без TTY: пауза `ask_user` без TTY автоматически разрешается пустым ответом вместо зависания.
```bash
# Один запрос, машиночитаемый
deeptutor run deep_solve "Find d/dx[sin(x^2)]" --tool reason --format json
# Цепочка ходов в одной сессии с состоянием — захватите id, повторно используйте его
SID=$(deeptutor run deep_research "Survey 2026 papers on RAG" \
--config mode=report --config depth=standard --format json \
| jq -r 'select(.type=="done").session_id')
deeptutor run deep_question "Quiz me on that survey" --session "$SID" --format json
```
В репозитории есть корневой [`SKILL.md`](SKILL.md) — документ передачи на ~150 строк, который знакомит любой использующий инструменты LLM со всей поверхностью за одно чтение. Передайте его Claude Code, Codex или OpenCode (они автоматически подхватывают `SKILL.md`), или оберните `deeptutor run` как инструмент в цикл LangChain / AutoGen. Полные рецепты: [Agent Handoff](https://deeptutor.info/docs/cli/agent-handoff/).
</details>
<details>
<summary><b>Справочник команд</b></summary>
| Команда | Описание |
|:---|:---|
| `deeptutor init` | Создать или обновить `data/user/settings` для текущего рабочего пространства |
| `deeptutor start [--home PATH]` | Запустить бэкенд + фронтенд вместе |
| `deeptutor serve [--port PORT]` | Запустить только бэкенд FastAPI |
| `deeptutor run <capability> <message>` | Запустить один ход возможности (`chat`, `deep_solve`, `deep_question`, `deep_research`, `visualize`, `math_animator`, `mastery_path`); добавьте `--format json` для вывода NDJSON |
| `deeptutor chat` | Интерактивный REPL с управлением возможностями, инструментами, KB, блокнотами и историей |
| `deeptutor partner list/create/start/stop` | Управление партнёрами, подключёнными к IM |
| `deeptutor kb list/info/create/add/search/set-default/delete` | Управление базами знаний LlamaIndex |
| `deeptutor skill search/install/list/remove/login/logout/publish/update` | Управление навыками, установка из хабов и публикация своих (`eduhub:<slug>` по умолчанию, см. Экосистема) |
| `deeptutor memory show/clear` | Просмотр документов памяти L2/L3 или очистка памяти L1/всей памяти |
| `deeptutor session list/show/open/rename/delete` | Управление общими сессиями |
| `deeptutor notebook list/create/show/add-md/replace-md/remove-record` | Управление блокнотами из файлов Markdown |
| `deeptutor book list/health/refresh-fingerprints` | Просмотр книг и обновление исходных отпечатков |
| `deeptutor plugin list/info` | Просмотр зарегистрированных инструментов и возможностей |
| `deeptutor config show` | Вывод сводки конфигурации |
| `deeptutor provider login <provider>` | Аутентификация провайдера (`openai-codex` вход через OAuth; `github-copilot` проверяет существующую сессию аутентификации Copilot) |
</details>
<details>
<summary><b>Дистрибутив только с CLI</b></summary>
Пакет только с CLI находится в `packaging/deeptutor-cli`. В этом чекауте установите его из исходного кода:
```bash
python -m pip install -e ./packaging/deeptutor-cli
```
Он ещё не опубликован в PyPI, поэтому основной раздел [Начало работы](#-начало-работы) сохраняет путь установки из исходного кода.
</details>
## 🧩 Экосистема — EduHub и Сообщество Навыков
Навыки DeepTutor используют открытый формат **Agent-Skills** — папку с плейбуком `SKILL.md` (YAML frontmatter + Markdown) и необязательными справочными файлами. В нём нет ничего специфичного для DeepTutor, поэтому любой реестр, говорящий на этом формате, становится источником для вашей библиотеки. DeepTutor поставляется с **[EduHub](https://eduhub.deeptutor.info/)** — нашим собственным образовательным реестром навыков — встроенным в качестве хаба по умолчанию.
<details>
<summary><b>EduHub — экосистема навыков DeepTutor</b></summary>
[**EduHub**](https://eduhub.deeptutor.info/) — это хаб сообщества, запущенный DeepTutor для обмена обучающими навыками агентов — сократовские репетиторы, создатели флэш-карточек, обратная связь по эссе, планы экзаменов, объяснители концепций и многое другое. Он встроен в DeepTutor, поэтому настраивать ничего не нужно: голый слаг или префикс `eduhub:` разрешается в него.
**Найти и установить** — в браузере откройте **Пространство Обучения → Навыки → Импорт из EduHub** для просмотра каталога и загрузки навыка прямо в вашу библиотеку. Из терминала:
```bash
deeptutor skill search "socratic tutor" # поиск в EduHub (хаб по умолчанию)
deeptutor skill install socratic-tutor # получить → проверить → зарегистрировать
deeptutor skill install eduhub:socratic-tutor@1.2.0 # указать хаб и версию
deeptutor skill list # локальные навыки с их хабовой принадлежностью
```
**Опубликуйте свой** — упакуйте `SKILL.md` и поделитесь им обратно с сообществом:
```bash
deeptutor skill login # вход через браузер в EduHub
deeptutor skill publish ./my-skill # интерактивно: выберите трек + теги, затем загрузите
deeptutor skill update # откатиться или выпустить новую версию
```
EduHub также является отдельным, совместимым с ClawHub реестром, поэтому агенты, отличные от DeepTutor (Claude Code, Codex, …), могут использовать его напрямую через CLI `eduhub``npx eduhub install socratic-tutor`.
</details>
<details>
<summary><b>Шлюз безопасности импорта</b></summary>
Независимо от источника, каждый импорт проходит через **один шлюз безопасности** перед тем, как что-либо коснётся вашего рабочего пространства:
- сначала проверяется **вердикт безопасности** реестра — отмеченные пакеты отклоняются, если вы не передали `--allow-unverified`;
- архивы извлекаются защищённо (защита от zip-slip / zip-bomb) за **белым списком суффиксов** для текста/скриптов, поэтому бинарные файлы никогда не попадают в рабочее пространство;
- frontmatter нормализуется по схеме DeepTutor, и `always:` **удаляется**, поэтому загруженный навык никогда не может принудить себя в каждый системный промпт;
- происхождение — хаб, версия, вердикт и время установки — записывается в `.hub-lock.json` для аудитов и обновлений.
В многопользовательских развёртываниях установка является исключительно привилегией администратора: новый навык попадает в каталог администратора и остаётся невидимым для других пользователей до тех пор, пока грант не назначит его, поэтому администратор может проверить его перед развёртыванием.
</details>
<details>
<summary><b>Также совместим с ClawHub</b></summary>
Поскольку DeepTutor использует открытый формат Agent-Skills, **[ClawHub](https://clawhub.ai/)** также работает как первоклассный источник — он встроен рядом с EduHub. Выберите его с префиксом хаба:
```bash
deeptutor skill search "git release notes" --hub clawhub
deeptutor skill install clawhub:git-release-notes@1.0.1
```
Добавляйте дополнительные реестры в `settings/skill_hubs.json`: запись `type: "clawhub"` указывает на любой совместимый HTTP API (EduHub и ClawHub оба его поддерживают), `type: "command"` оборачивает любой CLI получения, который поставляет реестр, а `"default"` выбирает хаб, используемый для голых слагов. Все они передаются через тот же шлюз импорта.
</details>
## 🌐 Сообщество
### 📮 Контакты
DeepTutor — это проект с открытым исходным кодом, который ведёт [Bingxi Zhao](https://github.com/pancacake) в составе группы [HKUDS](https://github.com/HKUDS), и он развивается в **полностью открытом формате**, создаваясь вместе с сообществом. До сих пор у нас **НЕТ** платных онлайн-продуктов в каком-либо виде. Не стесняйтесь обращаться по адресу **bingxizhao39@gmail.com** для обсуждений, идей или сотрудничества.
### 🙏 Благодарности
Сердечная благодарность [**Chao Huang**](https://sites.google.com/view/chaoh), директору Лаборатории интеллектуальных данных @ HKU, и нашим коллегам из HKUDS за их тёплую поддержку — особенно [**Jiahao Zhang**](https://github.com/zzhtx258), [**Zirui Guo**](https://github.com/LarFii) и [**Xubin Ren**](https://github.com/Re-bin). Мы также глубоко благодарны **сообществу открытого исходного кода**: ваши звёзды, вопросы, пул-реквесты и обсуждения каждый день формируют DeepTutor.
DeepTutor также стоит на плечах выдающихся проектов с открытым исходным кодом, которые дали нам инструменты и вдохновение:
| Проект | Роль / Вдохновение |
|:---|:---|
| [**LlamaIndex**](https://github.com/run-llama/llama_index) | Конвейер RAG и основа индексирования документов |
| [**nanobot**](https://github.com/HKUDS/nanobot) | Ультралёгкий движок агентов, обеспечивавший оригинальный TutorBot *(HKUDS)* |
| [**LightRAG**](https://github.com/HKUDS/LightRAG) | Простой и быстрый RAG *(HKUDS)* |
| [**AutoAgent**](https://github.com/HKUDS/AutoAgent) | Фреймворк агентов без кода *(HKUDS)* |
| [**AI-Researcher**](https://github.com/HKUDS/AI-Researcher) | Автоматизированный исследовательский конвейер *(HKUDS)* |
| [**OpenClaw**](https://github.com/openclaw/openclaw) | Открытый шлюз агентов и экосистема навыков за ClawHub |
| [**Codex**](https://github.com/openai/codex) | Агентный CLI кодирования, вдохновивший наш рабочий процесс CLI |
| [**Claude Code**](https://github.com/anthropics/claude-code) | Агентный CLI кодирования, вдохновивший цикл агента DeepTutor |
| [**ManimCat**](https://github.com/Wing900/ManimCat) | Генерация математической анимации на основе ИИ для Math Animator |
### 🗺️ Дорожная карта и участие
Мы хотим, чтобы DeepTutor продолжал развиваться и совершенствоваться — и в конечном итоге стал подарком, который мы возвращаем сообществу открытого исходного кода. Наша [**дорожная карта**](https://github.com/HKUDS/DeepTutor/issues/498) обновляется непрерывно; голосуйте там за пункты или предлагайте новые. Если вы хотите участвовать, см. [**Руководство по участию**](CONTRIBUTING.md) с описанием стратегии ветвления, стандартов кодирования и инструкций по началу работы.
<div align="center">
Мы надеемся, что DeepTutor станет подарком для сообщества. 🎁
<a href="https://github.com/HKUDS/DeepTutor/graphs/contributors">
<img src="https://contrib.rocks/image?repo=HKUDS/DeepTutor&max=999" alt="Участники" />
</a>
</div>
<div align="center">
<a href="https://www.star-history.com/#HKUDS/DeepTutor&type=timeline&legend=top-left">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=HKUDS/DeepTutor&type=timeline&theme=dark&legend=top-left" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=HKUDS/DeepTutor&type=timeline&legend=top-left" />
<img alt="Диаграмма истории звёзд" src="https://api.star-history.com/svg?repos=HKUDS/DeepTutor&type=timeline&legend=top-left" />
</picture>
</a>
</div>
<p align="center">
<a href="https://www.star-history.com/hkuds/deeptutor">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/badge?repo=HKUDS/DeepTutor&theme=dark" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/badge?repo=HKUDS/DeepTutor" />
<img alt="Рейтинг истории звёзд" src="https://api.star-history.com/badge?repo=HKUDS/DeepTutor" />
</picture>
</a>
</p>
<div align="center">
Лицензировано по [Apache License 2.0](LICENSE).
<p>
<img src="https://visitor-badge.laobi.icu/badge?page_id=HKUDS.DeepTutor&style=for-the-badge&color=00d4ff" alt="Views">
</p>
</div>
+707
View File
@@ -0,0 +1,707 @@
<div align="center">
<p align="center"><img src="../../assets/figs/logo/logo.png" alt="DeepTutor logo" height="56" style="vertical-align: middle;">&nbsp;<img src="../../assets/figs/logo/banner.png" alt="DeepTutor" height="48" style="vertical-align: middle;"></p>
# DeepTutor: การสอนพิเศษส่วนตัวตลอดชีวิต
<p align="center">
<a href="https://deeptutor.info" target="_blank"><img alt="Docs — deeptutor.info" src="https://img.shields.io/badge/Docs-deeptutor.info%20%E2%86%97-0A0A0A?style=for-the-badge&labelColor=F5F5F4" height="36"></a>
</p>
<p align="center">
<a href="https://trendshift.io/repositories/17099?utm_source=repository-badge&amp;utm_medium=badge&amp;utm_campaign=badge-repository-17099" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/repositories/17099" alt="HKUDS%2FDeepTutor | Trendshift" width="250" height="55"/></a>&nbsp;
<a href="https://trendshift.io/repositories/17099?utm_source=trendshift-badge&amp;utm_medium=badge&amp;utm_campaign=badge-trendshift-17099" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/17099/daily" alt="HKUDS%2FDeepTutor | Trendshift" width="250" height="55"/></a>&nbsp;
<a href="https://trendshift.io/repositories/17099?utm_source=trendshift-badge&amp;utm_medium=badge&amp;utm_campaign=badge-trendshift-17099" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/17099/weekly?language=Python" alt="HKUDS%2FDeepTutor | Trendshift" width="250" height="55"/></a>
</p>
<p align="center">
<a href="../../README.md"><img alt="English" height="40" src="https://img.shields.io/badge/English-CDCFD4"></a>&nbsp;
<a href="README_CN.md"><img alt="简体中文" height="40" src="https://img.shields.io/badge/简体中文-CDCFD4"></a>&nbsp;
<a href="README_JA.md"><img alt="日本語" height="40" src="https://img.shields.io/badge/日本語-CDCFD4"></a>&nbsp;
<a href="README_ES.md"><img alt="Español" height="40" src="https://img.shields.io/badge/Español-CDCFD4"></a>&nbsp;
<a href="README_FR.md"><img alt="Français" height="40" src="https://img.shields.io/badge/Français-CDCFD4"></a>&nbsp;
<a href="README_AR.md"><img alt="Arabic" height="40" src="https://img.shields.io/badge/Arabic-CDCFD4"></a>&nbsp;
<a href="README_RU.md"><img alt="Русский" height="40" src="https://img.shields.io/badge/Русский-CDCFD4"></a>&nbsp;
<a href="README_HI.md"><img alt="Hindi" height="40" src="https://img.shields.io/badge/Hindi-CDCFD4"></a>&nbsp;
<a href="README_PT.md"><img alt="Português" height="40" src="https://img.shields.io/badge/Português-CDCFD4"></a>&nbsp;
<a href="README_TH.md"><img alt="Thai" height="40" src="https://img.shields.io/badge/Thai-BCDCF7"></a>&nbsp;
<a href="README_PL.md"><img alt="Polski" height="40" src="https://img.shields.io/badge/Polski-CDCFD4"></a>
</p>
[![Python 3.11+](https://img.shields.io/badge/Python-3.11%2B-3776AB?style=flat-square&logo=python&logoColor=white)](https://www.python.org/downloads/)
[![Next.js 16](https://img.shields.io/badge/Next.js-16-000000?style=flat-square&logo=next.js&logoColor=white)](https://nextjs.org/)
[![License](https://img.shields.io/badge/License-Apache_2.0-blue?style=flat-square)](../../LICENSE)
[![GitHub release](https://img.shields.io/github/v/release/HKUDS/DeepTutor?style=flat-square&color=brightgreen)](https://github.com/HKUDS/DeepTutor/releases)
[![arXiv](https://img.shields.io/badge/arXiv-2604.26962-b31b1b?style=flat-square&logo=arxiv&logoColor=white)](https://arxiv.org/abs/2604.26962)
[![Discord](https://img.shields.io/badge/Discord-Community-5865F2?style=flat-square&logo=discord&logoColor=white)](https://discord.gg/eRsjPgMU4t)
[![Feishu](https://img.shields.io/badge/Feishu-Group-00D4AA?style=flat-square&logo=feishu&logoColor=white)](../../Communication.md)
[![WeChat](https://img.shields.io/badge/WeChat-Group-07C160?style=flat-square&logo=wechat&logoColor=white)](https://github.com/HKUDS/DeepTutor/issues/78)
[คุณสมบัติ](#-คุณสมบัติหลัก) · [เริ่มต้น](#-เริ่มต้น) · [สำรวจ](#-สำรวจ-deeptutor) · [CLI](#-deeptutor-cli--อินเทอร์เฟซ-agent-native) · [ระบบนิเวศ](#-ระบบนิเวศ--eduhub--ชุมชน-skills) · [ชุมชน](#-ชุมชน)
</div>
---
> 🤝 **เรายินดีรับการมีส่วนร่วมทุกรูปแบบ!** โหวตรายการ roadmap หรือเสนอรายการใหม่ที่ [`Roadmap`](https://github.com/HKUDS/DeepTutor/issues/498) และดู [คู่มือการมีส่วนร่วม](../../CONTRIBUTING.md) สำหรับกลยุทธ์ branching มาตรฐานการเขียนโค้ด และวิธีเริ่มต้น
### 📰 ข่าวสาร
- **2026-05-22** 🌐 เว็บไซต์เอกสารอย่างเป็นทางการเปิดตัวแล้วที่ [**deeptutor.info**](https://deeptutor.info/) — คู่มือ การอ้างอิง และ capability tours ทั้งหมดในที่เดียว
- **2026-04-19** 🎉 ถึง 20k stars ใน 111 วัน! ขอบคุณสำหรับการสนับสนุนที่มุ่งสู่การสอนพิเศษที่เป็นส่วนตัวและชาญฉลาดอย่างแท้จริง
- **2026-04-10** 📄 บทความของเราตอนนี้มีบน arXiv แล้ว! อ่าน [preprint](https://arxiv.org/abs/2604.26962) เพื่อเรียนรู้เกี่ยวกับการออกแบบและแนวคิดที่อยู่เบื้องหลัง DeepTutor
- **2026-02-06** 🚀 ถึง 10k stars ในเพียง 39 วัน! ขอบคุณชุมชนที่น่าเหลือเชื่ออย่างยิ่ง!
- **2026-01-01** 🎊 สวัสดีปีใหม่! เข้าร่วม [Discord](https://discord.gg/eRsjPgMU4t), [WeChat](https://github.com/HKUDS/DeepTutor/issues/78) หรือ [Discussions](https://github.com/HKUDS/DeepTutor/discussions) — มาร่วมกันกำหนดอนาคตของ DeepTutor
- **2025-12-29** 🎓 DeepTutor ได้รับการเปิดตัวอย่างเป็นทางการแล้ว!
## ✨ คุณสมบัติหลัก
DeepTutor คือ workspace การเรียนรู้แบบ agent-native ที่เชื่อมต่อการสอนพิเศษ, การแก้ปัญหา, การสร้าง quiz, การวิจัย, การสร้างภาพ และการฝึกความเชี่ยวชาญในระบบที่ขยายได้หนึ่งเดียว
- **รันไทม์เดียวสำหรับทุกโหมด** — Chat, Quiz, Research, Visualize, Solve และ Mastery Path บนลูป agent เดียวกัน คุณเปลี่ยนวัตถุประสงค์ ไม่ใช่เอ็นจิน และบริบทเดินทางไปพร้อมกับผู้เรียน
- **บริบทการเรียนรู้ที่เชื่อมต่อกัน** — ฐานความรู้, หนังสือ, ร่าง Co-Writer, สมุดบันทึก, คลังคำถาม, บุคลิกภาพ และ Memory พร้อมใช้งานในทุกเวิร์กโฟลว์ แทนที่จะอยู่ในเครื่องมือที่แยกจากกัน
- **ซับเอเจนต์และ Partners** — ปรึกษา Claude Code, Codex หรือ Partner แบบสดจากทุก turn (หรือนำเข้าบทสนทนาในอดีต) และรันเพื่อนถาวรบน IM ด้วยสมองเดียวกัน
- **ความรู้หลายเอ็นจิน** — ไลบรารี RAG แบบเวอร์ชันผ่าน LlamaIndex, PageIndex, GraphRAG, LightRAG หรือ Obsidian vault ที่เชื่อมโยง พร้อมการแยกวิเคราะห์เอกสารแบบ pluggable
- **เครื่องมือและทักษะที่ขยายได้** — เครื่องมือในตัว, เซิร์ฟเวอร์ MCP, โมเดลสร้างรูปภาพ/วิดีโอ/เสียง และทักษะชุมชนที่ติดตั้งได้จาก EduHub
- **หน่วยความจำที่ตรวจสอบได้** — การติดตาม L1, สรุปพื้นผิว L2 และการสังเคราะห์ L3 ทำให้การปรับแต่งส่วนบุคคลมองเห็นได้และแก้ไขได้ พร้อม Memory Graph ที่ติดตามทุกการอ้างสิทธิ์กลับไปสู่หลักฐาน
---
## 🚀 เริ่มต้น
DeepTutor มีเส้นทางการติดตั้งสี่เส้นทาง ทั้งหมดแชร์ layout workspace เดียว: การตั้งค่าอยู่ใน `data/user/settings/` ภายใต้ไดเร็กทอรีที่คุณเปิดตัว (หรือภายใต้ `DEEPTUTOR_HOME` / `deeptutor start --home` หากคุณตั้งค่าไว้อย่างชัดเจน) สำหรับแอปเต็มรูปแบบ ขั้นตอนที่แนะนำคือ **เลือกไดเร็กทอรี workspace → ติดตั้ง → `deeptutor init` → `deeptutor start`**
<details>
<summary><b>ตัวเลือกที่ 1 — ติดตั้งจาก PyPI</b> · แอป Web local แบบเต็มรูปแบบ + CLI ไม่ต้องโคลน</summary>
แอป Web local แบบเต็มรูปแบบ + CLI ไม่ต้องโคลน ต้องการ **Python 3.11+** และ runtime **Node.js 20+** บน PATH (เซิร์ฟเวอร์ standalone Next.js ที่แพ็คไว้จะถูกเปิดตัวโดย `deeptutor start`)
```bash
mkdir -p my-deeptutor && cd my-deeptutor
pip install -U deeptutor
deeptutor init # ขอพอร์ต + LLM provider + embedding แบบเสริม
deeptutor start # เริ่ม backend + frontend; เปิด terminal ไว้
```
`deeptutor init` จะขอพอร์ต backend (ค่าเริ่มต้น `8001`), พอร์ต frontend (ค่าเริ่มต้น `3782`), LLM provider / base URL / API key / model และ embedding provider แบบเสริมสำหรับ Knowledge Base / RAG
หลังจาก `deeptutor start` ให้เปิด URL ของ frontend ที่พิมพ์ใน terminal — ค่าเริ่มต้น [http://127.0.0.1:3782](http://127.0.0.1:3782) กด `Ctrl+C` ใน terminal นั้นเพื่อหยุดทั้ง backend และ frontend การข้าม `deeptutor init` ก็ใช้ได้สำหรับการทดลองอย่างรวดเร็ว แอปจะบูตด้วยพอร์ตเริ่มต้นและการตั้งค่า model ว่าง กำหนดค่าในภายหลังใน **Settings → Models**
</details>
<details>
<summary><b>ตัวเลือกที่ 2 — ติดตั้งจากซอร์สโค้ด</b> · พัฒนาจาก checkout</summary>
สำหรับการพัฒนาจาก checkout ใช้ **Python 3.11+** และ **Node.js 22 LTS** เพื่อให้ตรงกับ CI และ Docker
```bash
git clone https://github.com/HKUDS/DeepTutor.git
cd DeepTutor
# สร้าง venv (macOS/Linux). Windows PowerShell:
# py -3.11 -m venv .venv ; .\.venv\Scripts\Activate.ps1
python3 -m venv .venv && source .venv/bin/activate
python -m pip install --upgrade pip
# ติดตั้ง backend + frontend deps
python -m pip install -e .
( cd web && npm ci --legacy-peer-deps )
deeptutor init
deeptutor start
```
การติดตั้งจากซอร์สจะรัน Next.js ในโหมด dev กับไดเร็กทอรี `web/` ในเครื่อง ทุกอย่างอื่น (layout ของ config, พอร์ต, หยุดด้วย `Ctrl+C`) ตรงกับตัวเลือกที่ 1
<details>
<summary><b>สภาพแวดล้อม Conda</b> (แทน <code>venv</code>)</summary>
```bash
conda create -n deeptutor python=3.11
conda activate deeptutor
python -m pip install --upgrade pip
```
</details>
<details>
<summary><b>ส่วนเสริมการติดตั้ง</b> — dev / partners / matrix / math-animator</summary>
```bash
pip install -e ".[dev]" # เครื่องมือ tests/lint
pip install -e ".[partners]" # SDKs ช่องทาง IM ของ Partners + MCP client
pip install -e ".[matrix]" # ช่องทาง Matrix โดยไม่มี E2EE/libolm
pip install -e ".[matrix-e2e]" # Matrix E2EE; ต้องการ libolm
pip install -e ".[math-animator]" # Manim addon; ต้องการ LaTeX/ffmpeg/system libs
```
</details>
<details>
<summary><b>การปรับแก้ dependency ของ frontend และการแก้ปัญหาเซิร์ฟเวอร์ dev</b></summary>
**การเปลี่ยน dependency ของ frontend:** รัน `npm install --legacy-peer-deps` เพื่อรีเฟรช `web/package-lock.json` จากนั้น commit ทั้ง `web/package.json` และ `web/package-lock.json`
**เซิร์ฟเวอร์ dev ค้าง:** หาก `deeptutor start` รายงาน frontend ที่มีอยู่แต่ไม่ตอบสนอง ให้หยุด PID ที่พิมพ์ออกมา หากไม่มีกระบวนการ Next.js จริง ๆ ที่รันอยู่ ไฟล์ lock จะล้าสมัย — ลบออกแล้วลองใหม่:
```bash
rm -f web/.next/dev/lock web/.next/lock
deeptutor start
```
</details>
</details>
<details>
<summary><b>ตัวเลือกที่ 3 — Docker</b> · container เดียวที่ครบในตัว</summary>
Container เดียวสำหรับแอป Web แบบเต็มรูปแบบ ภาพบน GitHub Container Registry:
- `ghcr.io/hkuds/deeptutor:latest` — stable release
- `ghcr.io/hkuds/deeptutor:pre` — pre-release เมื่อพร้อมใช้งาน
> ดู [CONTAINERIZATION.md](../../CONTAINERIZATION.md) สำหรับการปรับใช้ podman/rootless/read-only-rootfs และคู่มือต่อการติดตั้งแบบครบถ้วน
```bash
docker run --rm --name deeptutor \
-p 127.0.0.1:3782:3782 \
-v deeptutor-data:/app/data \
ghcr.io/hkuds/deeptutor:latest
```
> **จำเป็นต้อง publish เฉพาะ `3782`** เบราว์เซอร์คุยกับ frontend origin เท่านั้น; Next.js middleware (`web/proxy.ts`) ส่งต่อ `/api/*` และ `/ws/*` ไปยัง FastAPI backend **ภายใน container** การ publish `8001` (`-p 127.0.0.1:8001:8001`) เป็นทางเลือก — มีประโยชน์เฉพาะเมื่อต้องการเรียก API โดยตรงด้วย curl หรือ scripts
เปิด [http://127.0.0.1:3782](http://127.0.0.1:3782) Container จะสร้าง `/app/data/user/settings/*.json` เมื่อบูตครั้งแรก กำหนดค่า model providers จากหน้า Web Settings Config, API keys, logs, ไฟล์ workspace, memory และ knowledge bases จะคงอยู่ใน volume `deeptutor-data`
- **พอร์ต host ที่แตกต่าง:** เปลี่ยนด้านซ้ายของการ mapping `-p host:container` แต่ละอัน (เช่น `-p 127.0.0.1:8088:3782`) หากคุณเปลี่ยนพอร์ตฝั่ง container ใน `/app/data/user/settings/system.json` ให้รีสตาร์ทและอัปเดตด้านขวาของการ mapping แต่ละอันให้ตรงกัน
- **แบบ detached:** เพิ่ม `-d` จากนั้น `docker logs -f deeptutor` เพื่อติดตาม, `docker stop deeptutor` เพื่อหยุด, `docker rm deeptutor` ก่อนนำชื่อมาใช้ซ้ำ Volume `deeptutor-data` จะเก็บการตั้งค่าและ workspace ของคุณข้ามการรีสตาร์ท
**Remote Docker / reverse proxy:** เบราว์เซอร์คุยกับ frontend origin (`:3782`) เท่านั้น; Next.js middleware ภายใน container ส่งต่อ `/api/*` และ `/ws/*` ไปยัง backend server-side สำหรับกรณี single-container ทั่วไปคุณไม่ต้องกำหนดค่า API base เลย — แค่ชี้ reverse proxy / TLS terminator ไปที่ `:3782` คุณต้องการ API base เฉพาะสำหรับ **split deployment** (backend ใน container/host แยกต่างหาก): ตั้งค่า `next_public_api_base` ใน `data/user/settings/system.json` เป็นที่อยู่ in-network ที่ frontend server ใช้เข้าถึง backend (อ่านฝั่ง server ไม่ส่งไปยังเบราว์เซอร์)
```json
{
"next_public_api_base": "http://backend:8001"
}
```
`next_public_api_base_external` (และ alias `public_api_base`) ยอมรับเป็น fallback ลำดับความสำคัญต่ำกว่า CORS ใช้ frontend **origins** ไม่ใช่ API URLs เมื่อปิด auth DeepTutor อนุญาต HTTP/HTTPS browser origins ปกติโดยค่าเริ่มต้น เมื่อเปิด auth ให้เพิ่ม frontend origins ที่แน่นอน:
```json
{
"cors_origins": ["https://deeptutor.example.com"]
}
```
<details>
<summary><b>การเชื่อมต่อกับ Ollama / LM Studio / llama.cpp / vLLM / Lemonade บน host</b></summary>
ภายใน Docker, `localhost` คือ container เอง ไม่ใช่เครื่อง host ของคุณ ในการเข้าถึง model service ที่รันบน host ให้ใช้ host gateway (แนะนำ):
```bash
docker run --rm --name deeptutor \
-p 127.0.0.1:3782:3782 -p 127.0.0.1:8001:8001 \
--add-host=host.docker.internal:host-gateway \
-v deeptutor-data:/app/data \
ghcr.io/hkuds/deeptutor:latest
```
จากนั้นใน **Settings → Models** ชี้ Base URL ของ provider ไปที่ `host.docker.internal`:
- Ollama LLM: `http://host.docker.internal:11434/v1`
- Ollama embedding: `http://host.docker.internal:11434/api/embed`
- LM Studio: `http://host.docker.internal:1234/v1`
- llama.cpp: `http://host.docker.internal:8080/v1`
- Lemonade: `http://host.docker.internal:13305/api/v1`
Docker Desktop (macOS/Windows) มักจะ resolve `host.docker.internal` ได้โดยไม่ต้องใช้ `--add-host` บน Linux ตัวเลือกนี้คือวิธีที่ portable ในการสร้าง hostname บน Docker Engine สมัยใหม่
**ทางเลือกบน Linux — host networking:** เพิ่ม `--network=host` และลบ flags `-p` ออก Container จะแชร์ network ของ host โดยตรง เปิด [http://127.0.0.1:3782](http://127.0.0.1:3782) (หรือ `frontend_port` ใน `system.json`) และ services ของ host สามารถเข้าถึงได้ด้วย localhost URLs ปกติ เช่น `http://127.0.0.1:11434/v1` โปรดทราบว่า host networking จะเปิดเผยพอร์ต container โดยตรงบน host และอาจขัดแย้งกับ services ที่มีอยู่ — หากต้องการเก็บไว้บน loopback ให้ตั้ง `BACKEND_HOST=127.0.0.1` และ `FRONTEND_HOST=127.0.0.1` (ดู [CONTAINERIZATION.md](../../CONTAINERIZATION.md))
</details>
</details>
<details>
<summary><b>ตัวเลือกที่ 4 — CLI เท่านั้น</b> · ไม่มี Web UI จาก source checkout</summary>
เมื่อคุณไม่ต้องการ Web UI แพ็คเกจ CLI-only ติดตั้งจาก source checkout ไม่ใช่จาก PyPI
```bash
git clone https://github.com/HKUDS/DeepTutor.git
cd DeepTutor
# สร้าง venv (macOS/Linux). Windows PowerShell:
# py -3.11 -m venv .venv-cli ; .\.venv-cli\Scripts\Activate.ps1
python3 -m venv .venv-cli && source .venv-cli/bin/activate
python -m pip install --upgrade pip
python -m pip install -e ./packaging/deeptutor-cli
deeptutor init --cli
deeptutor chat
```
`deeptutor init --cli` แชร์ layout `data/user/settings/` เดียวกับแอปเต็มรูปแบบ แต่ข้ามการขอพอร์ต backend/frontend และตั้งค่า embeddings เป็น **ปิด** โดยค่าเริ่มต้น (เลือก `Yes` หากคุณวางแผนใช้ `deeptutor kb …` หรือเครื่องมือ RAG) ยังคงเขียน layout runtime ที่ครบถ้วน (`system.json`, `auth.json`, `integrations.json`, `model_catalog.json`, `main.yaml`, `agents.yaml`) และยังคงขอ LLM provider และ model ที่ใช้งานอยู่
<details>
<summary><b>คำสั่งทั่วไป</b></summary>
```bash
deeptutor chat # interactive REPL
deeptutor chat --capability deep_solve --tool rag --kb my-kb
deeptutor run chat "Explain Fourier transform"
deeptutor run deep_solve "Solve x^2 = 4" --tool rag --kb my-kb
deeptutor kb create my-kb --doc textbook.pdf
deeptutor memory show
deeptutor config show
```
</details>
แพ็คเกจ `deeptutor-cli` ในเครื่องไม่มี Web assets หรือ server dependencies เก็บ source checkout ไว้ — การติดตั้งแบบ editable ชี้ไปที่มัน หากต้องการเพิ่มแอป Web ในภายหลัง ให้ติดตั้งแพ็คเกจ PyPI (ตัวเลือกที่ 1) และรัน `deeptutor init` + `deeptutor start` จาก workspace เดียวกัน
</details>
<details>
<summary><b>Sandbox การรันโค้ด (office skills)</b> · รันโค้ดที่ model สร้างสำหรับ docx / pdf / pptx / xlsx</summary>
office skills ที่ติดตั้งมา — **docx / pdf / pptx / xlsx** — ทำงานโดยให้ model เขียน Python script สั้น ๆ (`python-docx`, `reportlab`, `openpyxl`, …), รันผ่านเครื่องมือ `exec` / `code_execution` และส่งคืน URL ดาวน์โหลด เครื่องมือเหล่านี้จะ mount เมื่อ sandbox backend ทำงานอยู่ ซึ่งเป็น **ค่าเริ่มต้น** ในทุกรูปแบบการปรับใช้:
- **Local (ตัวเลือกที่ 1 / 2) และ Docker (ตัวเลือกที่ 3, single container):** sandbox ย่อย subprocess ที่จำกัดจะรันโค้ดของ model (บน host ในเครื่อง หรือภายใน container ภายใต้ Docker — container เป็น isolation boundary ของมันเอง)
- **docker-compose:** แทนที่จะเป็นเช่นนั้น จะ route ไปยัง **runner sidecar** ที่มีสิทธิ์น้อยที่สุดและมีความปลอดภัยสูง (`Dockerfile.runner`) ผ่าน `DEEPTUTOR_SANDBOX_RUNNER_URL` — ท่าทีที่แข็งแกร่งที่สุด และถูกเลือกโดยอัตโนมัติเมื่อมี
sandbox ย่อย subprocess ถูกควบคุมโดยการตั้งค่า `sandbox_allow_subprocess` ใน `data/user/settings/system.json` (ค่าเริ่มต้น `true`) การรันโค้ดที่ model สร้างบน host ของคุณเป็นการตัดสินใจด้านความน่าเชื่อถือจริง ๆ — ตั้งเป็น `false` (หรือ export `DEEPTUTOR_SANDBOX_ALLOW_SUBPROCESS=0`) เพื่อปิดการรันฝั่ง host โดยแลกกับ office skills ที่ไม่สามารถสร้างไฟล์ได้อีกต่อไป
</details>
<details>
<summary><b>เอกสารอ้างอิงการตั้งค่า</b> — ไฟล์การกำหนดค่าภายใต้ <code>data/user/settings/</code> (JSON/YAML)</summary>
ทุกอย่างภายใต้ `data/user/settings/` เป็น JSON/YAML ธรรมดา หน้า **Settings** ในเบราว์เซอร์คือโปรแกรมแก้ไขที่แนะนำ
| ไฟล์ | วัตถุประสงค์ |
|:---|:---|
| `model_catalog.json` | โปรไฟล์ provider LLM, embedding และ search; API keys; models ที่ใช้งานอยู่ |
| `system.json` | พอร์ต backend/frontend, public API base, CORS, SSL verification, ไดเร็กทอรีไฟล์แนบ |
| `auth.json` | สวิตช์ auth แบบเสริม, ชื่อผู้ใช้, password hash, การตั้งค่า token/cookie |
| `integrations.json` | การตั้งค่า PocketBase แบบเสริมและการรวม sidecar |
| `interface.json` | ความชอบภาษา / ธีม / แถบด้านข้างของ UI |
| `main.yaml` | ค่าเริ่มต้นพฤติกรรม runtime และการ inject path |
| `agents.yaml` | การตั้งค่า temperature และ token ของ capability/tool |
`.env` ที่ root ของโปรเจกต์จะ **ไม่** ถูกอ่านเป็นไฟล์ config ของแอปพลิเคชัน สำหรับการตั้งค่า model เบื้องต้น เปิด **Settings → Models** เพิ่มโปรไฟล์ LLM (Base URL / API key / ชื่อ model) และบันทึก เพิ่มโปรไฟล์ embedding เฉพาะเมื่อคุณวางแผนใช้ Knowledge Base / RAG features
</details>
## 📖 สำรวจ DeepTutor
เริ่มต้นด้วยพื้นผิวหลักที่คุณจะใช้ทุกวัน: Chat, Partners, My Agents, Co-Writer, Book, Knowledge Center, Learning Space, Memory และ Settings จากนั้นจะครอบคลุมการปรับใช้ Multi-User สำหรับ workspace แบบแชร์และแยกส่วน
<div align="center">
<img src="../../assets/figs/web-1.4.6+/OVERVIEW.png" alt="DeepTutor home — workspace Chat พร้อมทุกพื้นผิวใน sidebar" width="900">
</div>
<details>
<summary><b>🏗️ สถาปัตยกรรมระบบ</b></summary>
<div align="center">
<img src="../../assets/figs/system/system%20architecture.png" alt="สถาปัตยกรรมระบบ DeepTutor" width="900">
</div>
</details>
<details>
<summary><b>💬 Chat — ลูป Agent ที่คุณใช้จริง</b></summary>
Chat คือความสามารถเริ่มต้นและสถานที่ที่งานส่วนใหญ่เริ่มต้น thread เดียวสามารถพูดคุยตามปกติ, เรียกเครื่องมือ, อ้างอิงใน knowledge bases ที่เลือก, อ่านไฟล์แนบ, สร้างรูปภาพ, ปรึกษา subagents, เขียน notebook records และดำเนินการต่อด้วยบริบทเดียวกันตลอด turns
<div align="center">
<img src="../../assets/figs/web-1.4.6+/home/00-overview.png" alt="DeepTutor workspace chat" width="900">
</div>
ลูปนั้นเรียบง่ายโดยเจตนา: model คิดในรอบ ๆ, เรียกเครื่องมือเมื่อมีประโยชน์, สังเกตผลลัพธ์ และจบด้วยข้อความที่ไม่มีเครื่องมือ `ask_user` เป็นพิเศษ — แทนที่จะเดา agent สามารถหยุด turn, ถามคำถามชี้แจงที่มีโครงสร้าง และดำเนินการต่อเมื่อคุณตอบ
<div align="center">
<img src="../../assets/figs/system/chat-agent-loop.png" alt="DeepTutor chat agent loop" width="900">
</div>
เครื่องมือที่ผู้ใช้สลับได้ ได้แก่ `brainstorm`, `web_search`, `paper_search`, `reason`, และ `geogebra_analysis` — รวมถึง `imagegen` และ `videogen` เมื่อคุณกำหนดค่าโมเดลสร้างที่ตรงกัน เครื่องมือตามบริบทเช่น `rag`, `read_source`, `read_memory`, `write_memory`, `read_skill`, `load_tools`, `exec`, `web_fetch`, `ask_user`, `list_notebook`, `write_note`, `github`, และ `consult_subagent` จะ mount อัตโนมัติเมื่อ turn มีบริบทที่ถูกต้อง
บริบทมีสองประเภท: **sticky session context** (subagent, knowledge bases, persona, model, voice) อยู่บน composer toolbar และคงอยู่ตลอด turns; **one-time references** (ไฟล์, ประวัติ chat, หนังสือ, notebooks, question bank, imported agents) มาจากเมนู `+` สำหรับ turn เดียว
Chat ยังเป็นจุดเปิดตัวสำหรับความสามารถที่ลึกกว่า: **Quiz** สำหรับการสร้างคำถาม, **Research** สำหรับรายงานที่อ้างอิง, **Visualize** สำหรับ charts / diagrams / animations และ — ภายใต้ *More Capabilities***Solve** สำหรับการให้เหตุผลแบบมีขั้นตอน และ **Mastery Path** สำหรับ learning-plan flows
</details>
<details>
<summary><b>🤝 Partner — เพื่อนถาวรบนสมองเดียวกัน</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/partners/00-partners%20overview.png" alt="DeepTutor workspace partners" width="900">
</div>
Partners คือเพื่อนถาวรที่มี soul, นโยบาย model, ห้องสมุด, memory และช่องทางของตัวเอง พวกเขาไม่ใช่เอ็นจิน bot แยกต่างหาก: ทุกข้อความ web หรือ IM ที่เข้ามาจะกลายเป็น turn ปกติของ `ChatOrchestrator` ภายใน workspace ที่มีขอบเขต partner partner คือ "chat ที่มีบุคลิกภาพและหมายเลขโทรศัพท์"
<div align="center">
<img src="../../assets/figs/system/partners-architecture.png" alt="สถาปัตยกรรม partners DeepTutor" width="900">
</div>
แต่ละ partner มี `SOUL.md`, การเลือก model, ช่องทาง, นโยบายเครื่องมือ และห้องสมุดที่กำหนด Knowledge bases, skills และ notebooks ถูกคัดลอกไปยัง `data/partners/<id>/workspace/` ดังนั้น RAG, skill, notebook และเครื่องมือ memory เดิมทำงานได้โดยไม่มีกรณีพิเศษ partner อ่าน memory ของเจ้าของแต่เขียนเฉพาะของตัวเอง
<div align="center">
<img src="../../assets/figs/web-1.4.6+/partners/02-IM%20config%20for%20each%20partner.png" alt="การกำหนดค่าช่องทาง IM ต่อ partner" width="900">
</div>
ชั้น channel ที่ขับเคลื่อนด้วย schema สามารถเชื่อมต่อกับแพลตฟอร์ม IM ได้แก่ Feishu, Telegram, Slack, Discord, DingTalk, QQ/NapCat, WeCom, WhatsApp, Zulip, Mattermost, Matrix, Mochat และ Microsoft Teams ขึ้นอยู่กับ extras ที่ติดตั้งและ credentials ที่กำหนดค่า partner ยังสามารถเชื่อมต่อเป็น subagent และปรึกษาได้จาก chat turn ปกติ — ดู **My Agents** ด้านล่าง
</details>
<details>
<summary><b>🧑‍🚀 My Agents — ปรึกษาและนำเข้า Agents อื่น ๆ</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/myagents/00-overview.png" alt="DeepTutor workspace My Agents" width="900">
</div>
My Agents เปลี่ยน agent อื่น ๆ ให้กลายเป็นบริบทสำหรับ DeepTutor และทำสองสิ่งที่แตกต่างกัน **เชื่อมต่อ agent แบบสด** — Claude Code หรือ Codex CLI บนเครื่องของคุณ หรือหนึ่งใน Partners ของคุณ — และปรึกษามันจากภายใน chat turn: DeepTutor จริง ๆ *รัน* agent อื่นและ stream งานเข้าสู่แผง Activity ผ่านเครื่องมือ `consult_subagent` เลือกด้วย Agent chip (หรือพิมพ์ `@`) และตั้งค่าจำนวนรอบที่การปรึกษาอาจทำได้
<div align="center">
<img src="../../assets/figs/web-1.4.6+/home/08-subagent%20demo%20with%20claude%20code.png" alt="การปรึกษา subagent Claude Code แบบสด" width="900">
</div>
**นำเข้าบทสนทนาในอดีต** — นำประวัติ Claude Code และ Codex ที่มีอยู่ของคุณมาเป็น agent ที่มีชื่อ, ค้นหาได้ และสามารถดำเนินการต่อได้ เลือกวันที่จะนำเข้า การรีเฟรชจะ re-sync ข้อมูล อ้างอิงบทสนทนาที่นำเข้าจาก chat turn ใด ๆ ผ่าน `+` → My Agents และ DeepTutor จะอ่านมันเป็น transcript ของบุคคลที่สาม — มันยังคงเป็นบทสนทนา *ของพวกเขา* ไม่ใช่เสียงของ DeepTutor เอง
</details>
<details>
<summary><b>✍️ Co-Writer — การร่าง Markdown ที่รับรู้การเลือก</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/co-writer/00-overview.png" alt="DeepTutor workspace Co-Writer" width="900">
</div>
Co-Writer คือ workspace Markdown แบบ split-view สำหรับรายงาน, บทเรียน, บันทึก และ artifacts การเรียนรู้แบบยาว เอกสารบันทึกอัตโนมัติและแสดงตัวอย่างสด (คณิตศาสตร์ KaTeX, diagram fences) และสามารถบันทึกกลับเข้า notebooks เมื่อร่างกลายเป็นบริบทที่นำมาใช้ซ้ำได้
<div align="center">
<img src="../../assets/figs/web-1.4.6+/co-writer/01-edit%20panel.png" alt="Co-Writer editor พร้อม live preview" width="900">
</div>
แนวคิดหลักคือ **การแก้ไขแบบผ่าตัด**: เลือกช่วงและขอให้ DeepTutor เขียนใหม่, ขยาย หรือย่อ agent การแก้ไขสามารถอ้างอิงใน knowledge base หรือหลักฐานเว็บ, เก็บ trace ของ tool calls และแสดงทุกการเปลี่ยนแปลงเป็น accept/reject diff — ดังนั้นไม่มีอะไรลงจนกว่าคุณจะอนุมัติ
</details>
<details>
<summary><b>📖 Book — หนังสือมีชีวิตจากเนื้อหาของคุณ</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/book/00-book_overview.png" alt="DeepTutor book library" width="900">
</div>
Book แปลงแหล่งที่มาที่เลือกให้เป็น **หนังสือมีชีวิต** แบบโต้ตอบ — ไม่ใช่ PDF แบบคงที่ แต่เป็นสภาพแวดล้อมการอ่านที่สร้างจาก typed blocks หนังสือสามารถเริ่มจาก knowledge bases, notebooks, question banks หรือประวัติ chat; ขั้นตอนการสร้างจะเสนอ outline บทก่อนที่จะสร้างเนื้อหา ดังนั้นคุณจะตรวจสอบรูปร่างแทนที่จะยอมรับ output แบบ one-shot ที่มองไม่เห็น
<p align="center">
<img src="../../assets/figs/web-1.4.6+/book/01-book-demo-quiz%20card.png" alt="Book quiz block" width="31%">
&nbsp;
<img src="../../assets/figs/web-1.4.6+/book/02-book-demo-manim%20video.png" alt="Book Manim animation block" width="31%">
&nbsp;
<img src="../../assets/figs/web-1.4.6+/book/03-book-demo%20interactive%20module.png" alt="Book interactive widget block" width="31%">
</p>
แต่ละบทคอมไพล์เป็น typed blocks — text, callouts, quizzes, flash cards, timelines, code, figures, interactive HTML, animations, concept graphs, deep dives และ user notes — และทุกหน้ามี Page Chat ของตัวเอง Blocks สามารถแก้ไขได้: แทรก, ย้าย, สร้างใหม่ หรือเปลี่ยนประเภทของ block โดยไม่ต้องเขียนบทใหม่ คำสั่ง maintenance เช่น `deeptutor book health` และ `deeptutor book refresh-fingerprints` ช่วยตรวจจับว่าเมื่อใดที่ความรู้ต้นทางเปลี่ยนแปลงไปจากหน้าที่คอมไพล์แล้ว
</details>
<details>
<summary><b>📚 Knowledge Center — ไลบรารี RAG หลายเอ็นจิน</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/knowledge/00-overview.png" alt="DeepTutor Knowledge Center" width="900">
</div>
Knowledge bases คือคอลเลกชันเอกสารที่อยู่เบื้องหลัง RAG — รองรับ Chat turns, Co-Writer edits, Book generation และบทสนทนา Partner สิ่งที่โดดเด่นคือ **การเลือกเอ็นจิน retrieval**: **LlamaIndex** (ค่าเริ่มต้น, local vector + BM25), **PageIndex** (hosted, reasoning retrieval พร้อม page-level citations), **GraphRAG** และ **LightRAG** (knowledge-graph retrieval), **LightRAG Server** (retrieval ที่ offload ไปยัง LightRAG instance ภายนอกที่คุณเชื่อมต่อผ่าน HTTP) หรือ **Obsidian** vault ที่เชื่อมโยง tutor อ่านและเขียนในที่ KB แต่ละอันถูกผูกกับเอ็นจินหนึ่ง
<div align="center">
<img src="../../assets/figs/web-1.4.6+/knowledge/01-create%20knowledge%20base.png" alt="สร้าง knowledge base" width="900">
</div>
เมื่อสร้าง KB คุณ **สร้างใหม่** (อัพโหลดเอกสารและสร้าง index ใหม่) หรือ **เชื่อมโยงที่มีอยู่** (นำ index ที่สร้างไว้มาใช้ซ้ำ อ่านในที่โดยไม่ต้อง re-index) การ re-indexing จะเขียน directory `version-N` ใหม่และเก็บอันก่อนหน้าไว้ ดังนั้น index ที่ทำงานอยู่จะไม่ถูกทำลายระหว่างการสร้างใหม่ การแยกวิเคราะห์เอกสาร — Text-only, MinerU, Docling, markitdown หรือ PyMuPDF4LLM — ถูกเลือกใน **Settings → Knowledge Base** โดยการดาวน์โหลด local model ปิดโดยค่าเริ่มต้น CLI ครอบคลุม lifecycle ด้วย `deeptutor kb list`, `info`, `create`, `add`, `search`, `set-default` และ `delete`
</details>
<details>
<summary><b>🌐 Learning Space — Skills, Personas และบริบทที่นำมาใช้ซ้ำได้</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/learning-space/00-overview.png" alt="DeepTutor Learning Space hub" width="900">
</div>
Learning Space คือชั้น library และ personalization — ที่ซึ่งสิ่งที่คงอยู่ถาวรอาศัยอยู่ **Conversations & Materials** เก็บประวัติ chat, notebooks และ question bank (แต่ละคำถามที่บันทึกเก็บคำตอบของคุณ, คำตอบอ้างอิง และคำอธิบาย) **Personalization** เก็บ mastery paths, personas (พฤติกรรมที่ตั้งค่าล่วงหน้าเช่น *peer*, *research-assistant*, *teacher*) และ skills (`SKILL.md` playbooks ที่ model อ่านตามต้องการ) ทุกอย่างที่นี่สามารถนำมาใช้ซ้ำได้จาก Chat, Partners, Co-Writer และ Book
<div align="center">
<img src="../../assets/figs/web-1.4.6+/learning-space/07-%20download%20skills%20from%20eduhub.png" alt="นำเข้า skills จาก EduHub" width="900">
</div>
คุณไม่จำเป็นต้องเขียน skill ทุกอันเอง — **นำเข้าจาก EduHub** จะเรียกดู catalog ชุมชนและดาวน์โหลด skill ตรงเข้า library ผ่านประตูความปลอดภัย (ดู [ระบบนิเวศ](#-ระบบนิเวศ--eduhub--ชุมชน-skills))
</details>
<details>
<summary><b>🧠 Memory — การปรับแต่งส่วนบุคคลที่ตรวจสอบได้</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/memory/00-overview.png" alt="DeepTutor memory overview" width="900">
</div>
Memory คือระบบไฟล์สามชั้นที่คุณอ่าน, จัดการ และตรวจสอบได้ — โดยเจตนาไม่ใช่ vector store ที่ซ่อนอยู่ **L1** คือ workspace mirror พร้อม append-only event trace (`trace/<surface>/<date>.jsonl`); **L2** คือข้อเท็จจริงที่จัดการต่อพื้นผิว (`L2/<surface>.md`); **L3** คือการสังเคราะห์ข้ามพื้นผิว (`L3/<profile|recent|scope|preferences>.md`) เนื่องจาก L2 อ้างอิง L1 และ L3 อ้างอิง L2 ไม่มีอะไรในโปรไฟล์ของคุณที่ตรวจสอบไม่ได้
<div align="center">
<img src="../../assets/figs/web-1.4.6+/memory/01-3%20layer%20memory%20graph.png" alt="DeepTutor memory graph" width="900">
</div>
Memory Graph แสดงพีระมิดทั้งหมด — การสังเคราะห์ L3 ที่ศูนย์กลาง, L2 ในวงกลางกลาง, L1 traces ด้านนอก — เพื่อให้คุณติดตามการอ้างสิทธิ์ที่สังเคราะห์ใด ๆ กลับไปสู่เหตุการณ์ดิบที่แน่นอน Memory ถูกติดตามใน surfaces: `chat`, `notebook`, `quiz`, `kb`, `book`, partner และ `cowriter`; งบประมาณ Update / Audit / Dedup ของ consolidator ปรับได้ใน **Settings → Memory**
</details>
<details>
<summary><b>⚙️ Settings — Control Plane เดียว</b></summary>
<div align="center">
<img src="../../assets/figs/web-1.4.6+/settings/00-setting%20overview.png" alt="DeepTutor settings hub" width="900">
</div>
Settings คือ control plane การดำเนินงาน พร้อม live status strip (Backend, LLM, Embedding, Search) และหนึ่งการ์ดต่อพื้นที่: **Appearance** (ธีม + ภาษา UI), **Network** (API base, ports, CORS), **Models** (LLM, Embedding, Search, Text-to-Speech, Speech-to-Text, Image Generation, Video Generation), **Knowledge Base** (เอ็นจินการแยกวิเคราะห์เอกสาร), **Chat** (เครื่องมือ, MCP servers, พารามิเตอร์ต่อความสามารถ), **Partners & Agents** (subagents ที่คุณปรึกษาได้จาก turn) และ **Memory** (งบประมาณของ consolidator)
<div align="center">
<img src="../../assets/figs/web-1.4.6+/settings/01-appearance%20settings.png" alt="DeepTutor appearance settings and themes" width="900">
</div>
ส่วนส่วนใหญ่ใช้ draft-and-apply flow เพื่อให้คุณทดสอบ provider ก่อนยืนยัน ธีมสี่แบบมาในกล่อง — Default, Cream, Dark และ Glass ไฟล์ `.env` ที่ root ของโปรเจกต์ถูกเพิกเฉยโดยเจตนา; การกำหนดค่า runtime อยู่ใน `data/user/settings/*.json` เว้นแต่ `DEEPTUTOR_HOME` หรือ `deeptutor start --home` จะชี้แอปไปที่อื่น
</details>
<details>
<summary><b>👥 Multi-User — การปรับใช้แบบแชร์</b> · auth แบบเสริม, workspace ต่อผู้ใช้แบบแยกส่วน</summary>
การยืนยันตัวตน **ปิดอยู่โดยค่าเริ่มต้น** — DeepTutor ทำงานแบบผู้ใช้คนเดียว เปิดใช้งานและ tree `data/` หนึ่งจะโฮสต์ workspace ของ admin, workspace ต่อผู้ใช้แบบแยกส่วน และ workspace ของ partner ไว้ด้วยกัน:
```text
data/
├── user/ # Workspace ของ Admin + การตั้งค่าทั่วไป
├── users/<uid>/ # ขอบเขตต่อผู้ใช้: ประวัติ chat, memory, notebooks, KBs
├── partners/<id>/workspace/ # ขอบเขต partner (synthetic-user)
└── system/ # auth/users.json · grants/<uid>.json · audit/usage.jsonl
```
**ผู้ใช้คนแรกที่ลงทะเบียนจะกลายเป็น admin** และเป็นเจ้าของ model catalogs, provider credentials, shared knowledge bases, skills และ per-user grants ทุกคนอื่นจะได้รับ workspace แบบแยกส่วนและหน้า Settings ที่ถูก redact — models, KBs และ skills ที่ admin กำหนดจะแสดงเป็นตัวเลือก scoped แบบอ่านอย่างเดียว ไม่ใช่ API keys ดิบ
**เปิดใช้งาน:** เปิด auth ใน `data/user/settings/auth.json`, รีสตาร์ท `deeptutor start`, ลงทะเบียน admin คนแรกที่ `/register` จากนั้นเพิ่มผู้ใช้จาก `/admin/users` และกำหนด models, KBs, skills, Partners, นโยบาย tool/MCP และสิทธิ์การรันโค้ดผ่าน grants
> PocketBase ยังคงเป็น integration สำหรับผู้ใช้คนเดียว — เว้น `integrations.pocketbase_url` ว่างสำหรับการปรับใช้ multi-user เว้นแต่คุณจะเชื่อมต่อ user store ภายนอก
</details>
## ⌨️ DeepTutor CLI — อินเทอร์เฟซ Agent-Native
binary `deeptutor` เดียว, สองวิธีเข้า: **REPL** แบบโต้ตอบสำหรับคนที่อยู่ใน terminal และ **JSON** ที่มีโครงสร้างสำหรับ agents อื่น ๆ ที่ขับเคลื่อน DeepTutor เป็นเครื่องมือ ความสามารถ, เครื่องมือ และ knowledge bases เหมือนกันทั้งสองแบบ
<details>
<summary><b>ขับเคลื่อนด้วยตัวเอง</b></summary>
`deeptutor chat` เปิด interactive REPL; `deeptutor run <capability> "<message>"` รัน turn เดียวแล้วออก ทั้งสองใช้ flags `--capability`, `--tool`, `--kb` และ `--config` เหมือนกัน
```bash
deeptutor chat # interactive REPL
deeptutor chat --capability deep_solve --kb my-kb --tool rag
deeptutor run chat "Explain the Fourier transform" --tool rag --kb textbook
deeptutor run deep_research "Survey 2026 papers on RAG" \
--config mode=report --config depth=standard
```
ทุกอย่างที่แอป Web ทำก็มีที่นี่ด้วย — knowledge bases (`kb`), sessions (`session`), partners (`partner`), skills (`skill`), notebooks, memory และ config รายการเต็มด้านล่าง
</details>
<details>
<summary><b>ให้ agent ขับเคลื่อน</b></summary>
DeepTutor ถูกสร้างมาเพื่อ *ดำเนินการโดย agent อื่น* เพิ่ม `--format json` ใน `run` ใด ๆ และแต่ละ turn จะ stream **NDJSON — หนึ่ง event ต่อบรรทัด** (`content`, `tool_call`, `tool_result`, `done`, …) ทุกบรรทัดมี `session_id` กำกับ การรันปลอดภัยสำหรับ headless: การหยุด `ask_user` ที่ไม่มี TTY จะ auto-resolve ด้วยการตอบกลับว่างแทนที่จะหยุดรอ
```bash
# One shot แบบ machine-readable
deeptutor run deep_solve "Find d/dx[sin(x^2)]" --tool reason --format json
# เชื่อม turns ใน session เดียวที่มีสถานะ — จับ id แล้วนำมาใช้ซ้ำ
SID=$(deeptutor run deep_research "Survey 2026 papers on RAG" \
--config mode=report --config depth=standard --format json \
| jq -r 'select(.type=="done").session_id')
deeptutor run deep_question "Quiz me on that survey" --session "$SID" --format json
```
repo มี root [`SKILL.md`](../../SKILL.md) — เอกสาร handover ~150 บรรทัดที่สอน LLM ที่ใช้เครื่องมือใด ๆ ให้รู้จัก surface ทั้งหมดในการอ่านครั้งเดียว ส่งให้ Claude Code, Codex หรือ OpenCode (พวกเขาหยิบ `SKILL.md` โดยอัตโนมัติ) หรือ wrap `deeptutor run` เป็นเครื่องมือใน LangChain / AutoGen loop สูตรเต็ม: [Agent Handoff](https://deeptutor.info/docs/cli/agent-handoff/)
</details>
<details>
<summary><b>เอกสารอ้างอิงคำสั่ง</b></summary>
| คำสั่ง | คำอธิบาย |
|:---|:---|
| `deeptutor init` | สร้างหรืออัพเดต `data/user/settings` สำหรับ workspace ปัจจุบัน |
| `deeptutor start [--home PATH]` | เปิดตัว backend + frontend ด้วยกัน |
| `deeptutor serve [--port PORT]` | เริ่มเฉพาะ FastAPI backend |
| `deeptutor run <capability> <message>` | รัน capability turn เดียว (`chat`, `deep_solve`, `deep_question`, `deep_research`, `visualize`, `math_animator`, `mastery_path`); เพิ่ม `--format json` สำหรับ NDJSON output |
| `deeptutor chat` | Interactive REPL พร้อม capability, tool, KB, notebook และ history controls |
| `deeptutor partner list/create/start/stop` | จัดการ partners ที่เชื่อมต่อผ่าน IM |
| `deeptutor kb list/info/create/add/search/set-default/delete` | จัดการ knowledge bases LlamaIndex |
| `deeptutor skill search/install/list/remove/login/logout/publish/update` | จัดการทักษะ ติดตั้งจากฮับ และเผยแพร่ของคุณเอง (`eduhub:<slug>` โดยค่าเริ่มต้น ดู Ecosystem) |
| `deeptutor memory show/clear` | ตรวจสอบ L2/L3 memory docs หรือล้าง L1/all memory |
| `deeptutor session list/show/open/rename/delete` | จัดการ shared sessions |
| `deeptutor notebook list/create/show/add-md/replace-md/remove-record` | จัดการ notebooks จากไฟล์ Markdown |
| `deeptutor book list/health/refresh-fingerprints` | ตรวจสอบ books และรีเฟรช source fingerprints |
| `deeptutor plugin list/info` | ตรวจสอบเครื่องมือและ capabilities ที่ลงทะเบียน |
| `deeptutor config show` | พิมพ์สรุปการกำหนดค่า |
| `deeptutor provider login <provider>` | Provider auth (OAuth login สำหรับ `openai-codex`; `github-copilot` ตรวจสอบ session auth Copilot ที่มีอยู่) |
</details>
<details>
<summary><b>การแจกจ่าย CLI เท่านั้น</b></summary>
แพ็คเกจ CLI เท่านั้นอยู่ใน `packaging/deeptutor-cli` ใน checkout นี้ ติดตั้งจากซอร์ส:
```bash
python -m pip install -e ./packaging/deeptutor-cli
```
ยังไม่ได้เผยแพร่บน PyPI ดังนั้นส่วน [เริ่มต้น](#-เริ่มต้น) หลักจึงคงเส้นทางการติดตั้งจากซอร์สไว้
</details>
## 🧩 ระบบนิเวศ — EduHub และชุมชน Skills
DeepTutor skills ใช้รูปแบบ **Agent-Skills** แบบเปิด — โฟลเดอร์ที่มี `SKILL.md` playbook (YAML frontmatter + Markdown) และไฟล์อ้างอิงแบบเสริม ไม่มีอะไรเกี่ยวกับมันที่เจาะจงสำหรับ DeepTutor ดังนั้น registry ใด ๆ ที่พูด format นี้ก็กลายเป็นแหล่งสำหรับ library ของคุณ DeepTutor มาพร้อมกับ **[EduHub](https://eduhub.deeptutor.info/)** — registry ทักษะที่เน้นการศึกษาของเรา — เชื่อมต่อเป็นฮับเริ่มต้น
<details>
<summary><b>EduHub — ระบบนิเวศทักษะของ DeepTutor</b></summary>
[**EduHub**](https://eduhub.deeptutor.info/) คือ community hub ที่ DeepTutor เปิดตัวสำหรับแชร์ agent skills เชิงสอน — Socratic tutors, flashcard builders, essay feedback, exam blueprints, concept explainers และอื่น ๆ อีกมาก มันถูกสร้างเข้า DeepTutor ดังนั้นไม่มีอะไรต้องกำหนดค่า: slug เปล่าหรือ prefix `eduhub:` จะ resolve ไปยังมัน
**ค้นหาและติดตั้ง** — ในเบราว์เซอร์ เปิด **Learning Space → Skills → นำเข้าจาก EduHub** เพื่อเรียกดู catalog และดาวน์โหลด skill ตรงเข้า library จาก terminal:
```bash
deeptutor skill search "socratic tutor" # ค้นหา EduHub (ฮับเริ่มต้น)
deeptutor skill install socratic-tutor # fetch → verify → register
deeptutor skill install eduhub:socratic-tutor@1.2.0 # ระบุ hub และเวอร์ชัน
deeptutor skill list # skills ในเครื่องพร้อม hub provenance
```
**เผยแพร่ของคุณเอง** — แพ็ค `SKILL.md` และแชร์กลับสู่ชุมชน:
```bash
deeptutor skill login # browser sign-in ไปยัง EduHub
deeptutor skill publish ./my-skill # interactive: เลือก track + tags แล้วอัพโหลด
deeptutor skill update # rollback หรือ release เวอร์ชันใหม่
```
EduHub ยังเป็น registry แบบ standalone ที่เข้ากันได้กับ ClawHub ดังนั้น agents ที่ไม่ใช่ DeepTutor (Claude Code, Codex, …) สามารถใช้มันโดยตรงผ่าน CLI `eduhub``npx eduhub install socratic-tutor`
</details>
<details>
<summary><b>ประตูความปลอดภัยในการนำเข้า</b></summary>
ไม่ว่าแหล่งที่มาจะเป็นอะไร ทุกการนำเข้าจะผ่าน **ประตูความปลอดภัยเดียวกัน** ก่อนที่อะไรจะแตะ workspace ของคุณ:
- **security verdict** ของ registry จะถูกตรวจสอบก่อน — แพ็คเกจที่ถูกตั้งค่าสถานะจะถูกปฏิเสธเว้นแต่คุณจะส่ง `--allow-unverified`;
- archives จะถูก extract อย่างระมัดระวัง (ป้องกัน zip-slip / zip-bomb) หลัง **suffix whitelist** แบบ text/script ดังนั้น binaries จะไม่ลงใน workspace เลย;
- frontmatter จะถูก normalize เป็น schema ของ DeepTutor และ `always:` จะถูก **ลบออก** ดังนั้น skill ที่ดาวน์โหลดมาไม่สามารถบังคับตัวเองเข้าสู่ system prompt ทุกอัน;
- provenance — hub, version, verdict และเวลาติดตั้ง — จะถูกเขียนลง `.hub-lock.json` สำหรับการตรวจสอบและอัพเดต
ในการปรับใช้ multi-user การติดตั้งเป็นสิทธิ์ของ admin เท่านั้น: skill ใหม่จะลงใน admin catalog และมองไม่เห็นสำหรับผู้ใช้อื่นจนกว่า grant จะกำหนดมัน ดังนั้น admin สามารถตรวจสอบก่อนนำออกใช้
</details>
<details>
<summary><b>รองรับ ClawHub ด้วย</b></summary>
เนื่องจาก DeepTutor พูดรูปแบบ Agent-Skills แบบเปิด **[ClawHub](https://clawhub.ai/)** ทำงานเป็นแหล่งระดับ first-class ด้วย — มันถูกสร้างเข้าพร้อมกับ EduHub เลือกด้วย hub prefix:
```bash
deeptutor skill search "git release notes" --hub clawhub
deeptutor skill install clawhub:git-release-notes@1.0.1
```
เพิ่ม registries เพิ่มเติมใน `settings/skill_hubs.json`: entry `type: "clawhub"` ชี้ไปที่ HTTP API ที่เข้ากันได้ใด ๆ (ทั้ง EduHub และ ClawHub พูด API นี้), `type: "command"` ห่อ CLI ที่ registry ส่งมา และ `"default"` เลือกฮับที่ใช้สำหรับ slugs เปล่า ทั้งหมดนี้ป้อนข้อมูลผ่านประตูนำเข้าเดียวกัน
</details>
## 🌐 ชุมชน
### 📮 ติดต่อ
DeepTutor คือโปรเจกต์โอเพนซอร์สที่นำโดย [Bingxi Zhao](https://github.com/pancacake) ภายในกลุ่ม [HKUDS](https://github.com/HKUDS) และพัฒนาใน **รูปแบบโอเพนซอร์สอย่างสมบูรณ์** สร้างร่วมกับชุมชน จนถึงปัจจุบัน เรา **ไม่มี** ผลิตภัณฑ์ออนไลน์แบบชำระเงินในรูปแบบใด ๆ ติดต่อได้ที่ **bingxizhao39@gmail.com** สำหรับการสนทนา, ไอเดีย หรือการร่วมมือ
### 🙏 ขอบคุณ
ขอบคุณอย่างจริงใจถึง [**Chao Huang**](https://sites.google.com/view/chaoh), ผู้อำนวยการ Data Intelligence Lab @ HKU และเพื่อน ๆ ใน HKUDS lab สำหรับการสนับสนุนอย่างอบอุ่น — โดยเฉพาะ [**Jiahao Zhang**](https://github.com/zzhtx258), [**Zirui Guo**](https://github.com/LarFii) และ [**Xubin Ren**](https://github.com/Re-bin) เรายังขอบคุณอย่างสุดซึ้งถึง **ชุมชนโอเพนซอร์ส**: stars, issues, pull requests และ discussions ของคุณกำหนดรูปร่าง DeepTutor ทุกวัน
DeepTutor ยังยืนอยู่บนไหล่ของโปรเจกต์โอเพนซอร์สที่โดดเด่นที่ให้ทั้งเครื่องมือและแรงบันดาลใจแก่เรา:
| โปรเจกต์ | บทบาท / แรงบันดาลใจ |
|:---|:---|
| [**LlamaIndex**](https://github.com/run-llama/llama_index) | กระดูกสันหลังของ RAG pipeline และการ indexing เอกสาร |
| [**nanobot**](https://github.com/HKUDS/nanobot) | Ultra-lightweight agent engine ที่ขับเคลื่อน TutorBot ดั้งเดิม *(HKUDS)* |
| [**LightRAG**](https://github.com/HKUDS/LightRAG) | RAG ที่ง่ายและเร็ว *(HKUDS)* |
| [**AutoAgent**](https://github.com/HKUDS/AutoAgent) | Zero-code agent framework *(HKUDS)* |
| [**AI-Researcher**](https://github.com/HKUDS/AI-Researcher) | Pipeline การวิจัยอัตโนมัติ *(HKUDS)* |
| [**OpenClaw**](https://github.com/openclaw/openclaw) | Open agent gateway และ skill ecosystem เบื้องหลัง ClawHub |
| [**Codex**](https://github.com/openai/codex) | Agent-native coding CLI ที่เป็นแรงบันดาลใจให้ CLI workflow ของเรา |
| [**Claude Code**](https://github.com/anthropics/claude-code) | Agentic coding CLI ที่เป็นแรงบันดาลใจให้ DeepTutor agent loop |
| [**ManimCat**](https://github.com/Wing900/ManimCat) | การสร้าง animation คณิตศาสตร์ที่ขับเคลื่อนด้วย AI สำหรับ Math Animator |
### 🗺️ Roadmap และการมีส่วนร่วม
เราต้องการให้ DeepTutor พัฒนาและปรับปรุงต่อเนื่อง — และสุดท้ายกลายเป็นของขวัญที่เรามอบคืนสู่ชุมชนโอเพนซอร์ส [**roadmap**](https://github.com/HKUDS/DeepTutor/issues/498) ของเราอัพเดตต่อเนื่อง โหวตรายการที่นั่นหรือเสนอรายการใหม่ หากต้องการมีส่วนร่วม ดู [**คู่มือการมีส่วนร่วม**](../../CONTRIBUTING.md) สำหรับกลยุทธ์ branching มาตรฐานโค้ด และวิธีเริ่มต้น
<div align="center">
เราหวังว่า DeepTutor จะกลายเป็นของขวัญสำหรับชุมชน 🎁
<a href="https://github.com/HKUDS/DeepTutor/graphs/contributors">
<img src="https://contrib.rocks/image?repo=HKUDS/DeepTutor&max=999" alt="ผู้มีส่วนร่วม" />
</a>
</div>
<div align="center">
<a href="https://www.star-history.com/#HKUDS/DeepTutor&type=timeline&legend=top-left">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=HKUDS/DeepTutor&type=timeline&theme=dark&legend=top-left" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=HKUDS/DeepTutor&type=timeline&legend=top-left" />
<img alt="กราฟประวัติดาว" src="https://api.star-history.com/svg?repos=HKUDS/DeepTutor&type=timeline&legend=top-left" />
</picture>
</a>
</div>
<p align="center">
<a href="https://www.star-history.com/hkuds/deeptutor">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/badge?repo=HKUDS/DeepTutor&theme=dark" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/badge?repo=HKUDS/DeepTutor" />
<img alt="อันดับประวัติดาว" src="https://api.star-history.com/badge?repo=HKUDS/DeepTutor" />
</picture>
</a>
</p>
<div align="center">
ได้รับอนุญาตภายใต้ [Apache License 2.0](../../LICENSE)
<p>
<img src="https://visitor-badge.laobi.icu/badge?page_id=HKUDS.DeepTutor&style=for-the-badge&color=00d4ff" alt="จำนวนผู้เข้าชม">
</p>
</div>
Binary file not shown.

After

Width:  |  Height:  |  Size: 882 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 977 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 442 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 280 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 732 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 579 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 409 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 171 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 423 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 399 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 414 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 984 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 148 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 198 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 193 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 107 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 893 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 147 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 446 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 569 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 624 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 554 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 614 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 235 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 245 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 206 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 631 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 206 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 144 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 103 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 97 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 84 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 157 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 677 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 572 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 236 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 161 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 267 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 403 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 442 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 321 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 286 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 200 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 289 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 379 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 317 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 237 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 377 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 400 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 356 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 258 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 259 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 405 KiB

Some files were not shown because too many files have changed in this diff Show More