Jump to content

Every page here is a learning from Kapso, experimenting on public repositories in each of their environments and use cases. Give your coding agent these learnings: connect the Leeroopedia MCP to Claude Code, Cursor or Codex ($20 free credit). Powered by Leeroo · founders@leeroo.com

Environment:1Panel dev MaxKB Django

From Leeroopedia
Knowledge Sources
Domains Infrastructure, Web_Framework, Deployment
Last Updated 2026-10-10 00:00 GMT

Overview

Python 3.11 with Django 5.2, DRF, and LangChain, providing the full web application stack for MaxKB's admin API and chat runtime.

Description

This environment provides the core Django web application stack for MaxKB. It includes Django 5.2.16 with Django REST Framework, drf-spectacular for OpenAPI documentation, and the full LangChain integration (1.3.x) for LLM orchestration. The stack supports two runtime modes: `web` (full Django app with all `INSTALLED_APPS`, DB, cache, REST framework) and `local_model` (minimal settings for the embedding/reranker model server). The runtime mode is selected via the `SERVER_NAME` environment variable, set by `main.py` based on the service being started.

Usage

Use this environment for any MaxKB service: the web server (Django/gunicorn on port 8080), the Celery worker, or the local model server (port 11636). It is the mandatory prerequisite for all non-RAG-specific implementations including WorkflowManage, MCPToolHandler, ConfigManager, main_py, and all other Django-based implementations.

System Requirements

Category Requirement Notes
OS Linux (Ubuntu 20.04+ recommended) macOS and Windows supported in dev mode
Hardware 2+ CPU cores, 4GB+ RAM 8GB+ recommended for local model embeddings
Disk 10GB+ for app, 2GB+ for bundled models Models stored at `/opt/maxkb-app/model/base`
Software Python 3.11 (pinned `~=3.11.0`) `uv` package manager required

Dependencies

System Packages

  • `python3.11`
  • `uv` (package manager; uses `uv.lock`)
  • `nodejs` >= 18 and `npm` (for frontend build only)
  • `gunicorn` (production WSGI server)
  • `gcc` / build tools (for compiling `sandbox.so`)

Python Packages

  • `django` == 5.2.16
  • `djangorestframework` == 3.17.2
  • `drf-spectacular[sidecar]` == 0.28.0
  • `django-redis` == 6.0.0
  • `django-db-connection-pool` == 1.2.6
  • `django-mptt` == 0.17.0
  • `django-celery-beat` == 2.8.1
  • `django-apscheduler` == 0.7.0
  • `langchain` == 1.3.10
  • `langchain-core` == 1.4.8
  • `langchain-openai` == 1.3.2
  • `langchain-anthropic` == 1.4.6
  • `langchain-community` == 0.4.2
  • `langchain-mcp-adapters` == 0.3.0
  • `mcp` == 1.28.1
  • `langgraph` == 1.2.6
  • `torch` == 2.13.0 (CPU-only on Linux)
  • `sentence-transformers` == 5.0.0
  • `numpy` == 1.26.4
  • `gunicorn` == 23.0.0
  • `python-daemon` == 3.1.2
  • `pytz` == 2025.2
  • `psutil` == 7.0.0
  • `cryptography` == 50.0.0
  • `jieba` == 0.42.1 (Chinese text segmentation)

Credentials

The following environment variables must be set (via `MAXKB_` env prefix or YAML config):

  • `MAXKB_CONFIG_TYPE`: `ENV` to read from env vars, or `FILE` to read YAML from `/opt/maxkb/conf`
  • `MAXKB_SECRET_KEY`: Django secret key (auto-generated if not set)
  • `MAXKB_LANGUAGE_CODE`: UI language (default `zh-CN`)
  • `MAXKB_TIME_ZONE`: Timezone (default `Asia/Shanghai`)
  • `MAXKB_ADMIN_PATH`: Admin API path prefix (default `/admin`)
  • `MAXKB_CHAT_PATH`: Chat API path prefix (default `/chat`)
  • `MAXKB_DEBUG`: Debug mode (default `True` in dev, `False` in production)
  • `MAXKB_LOCAL_MODEL_HOST`: Local model server host (default `127.0.0.1`)
  • `MAXKB_LOCAL_MODEL_PORT`: Local model server port (default `11636`)
  • `SERVER_NAME`: Runtime mode selector (`web` or `local_model`); set automatically by `main.py`
  • `MAXKB_SANDBOX_PYTHON_BANNED_KEYWORDS`: Banned keywords for sandbox Python execution
  • `MAXKB_SANDBOX_PYTHON_BANNED_HOSTS`: Banned hosts for sandbox network access
  • `MAXKB_SANDBOX_PYTHON_PACKAGE_PATHS`: Pre-installed packages for sandbox (default: `/opt/py3/lib/python3.11/site-packages,...`)
  • `MAXKB_DATA_UPLOAD_MAX_MEMORY_SIZE`: Max upload size in bytes (default 100MB)

Quick Install

# Clone and install with uv
git clone https://github.com/1Panel-dev/MaxKB.git
cd MaxKB
uv sync

# Run database migrations
python main.py upgrade_db

# Collect static files (frontend must be built first)
cd ui && npm install && npm run build && npm run build-chat && cd ..
python main.py collect_static

# Start development server
python main.py dev web      # Django runserver on 0.0.0.0:8080
python main.py dev celery   # Celery worker
python main.py dev local_model  # Local embedding model on 127.0.0.1:11636

Code Evidence

Settings dispatch based on `SERVER_NAME` from `apps/maxkb/settings/base/__init__.py` (referenced in `main.py:134-137`):

if services.__contains__('web'):
    os.environ.setdefault('SERVER_NAME', 'web')
elif services.__contains__('local_model'):
    os.environ.setdefault('SERVER_NAME', 'local_model')

Full `INSTALLED_APPS` for web mode from `apps/maxkb/settings/base/web.py:30-49`:

INSTALLED_APPS = [
    'django.contrib.contenttypes',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'drf_spectacular',
    'drf_spectacular_sidecar',
    'users.apps.UsersConfig',
    'tools.apps.ToolConfig',
    'knowledge',
    'common',
    'system_manage',
    'models_provider',
    'django_celery_beat',
    'application',
    'chat',
    'oss',
    'trigger',
    'django_apscheduler',
]

Minimal `INSTALLED_APPS` for local_model mode from `apps/maxkb/settings/base/model.py:31-37`:

INSTALLED_APPS = [
    'django.contrib.contenttypes',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'local_model',
]

Python version pin from `pyproject.toml:6`:

requires-python = "~=3.11.0"

DB crash recovery retry logic from `main.py:33-63`:

def perform_db_migrate():
    """wait-for-it 仅检测 TCP 端口,PostgreSQL 崩溃恢复期间端口已开放但拒绝查询,
    因此在此处增加重试逻辑,等待数据库真正就绪后再执行 migrate。"""
    max_retries = 10
    retry_interval = 5  # seconds
    for attempt in range(1, max_retries + 1):
        try:
            management.call_command('migrate')
            return
        except Exception as e:
            is_db_starting = (
                    'the database system is starting up' in err_msg
                    or 'starting up' in err_msg
                    or 'Connection refused' in err_msg
            )
            if is_db_starting and attempt < max_retries:
                logging.warning(f'Database is not ready yet (attempt {attempt}/{max_retries})...')
                time.sleep(retry_interval)

Common Errors

Error Message Cause Solution
`No module named 'maxkb.settings'` `DJANGO_SETTINGS_MODULE` not set Ensure `main.py` is the entrypoint; it sets `sys.path` and env vars
`ModuleNotFoundError: No module named 'application'` Wrong working directory or `sys.path` Run from project root; `main.py` inserts `apps/` on `sys.path`
`SECRET_KEY not set` Missing `MAXKB_SECRET_KEY` Auto-generated by `main.py`; set explicitly for production consistency
`TypeError: 'NoneType' object is not iterable` in settings Wrong `SERVER_NAME` loads wrong app set Verify `SERVER_NAME` is `web` or `local_model`; check `main.py` service arg
`Static files not found` Frontend not built Run `npm run build` and `npm run build-chat` in `ui/`, then `python main.py collect_static`

Compatibility Notes

  • Python version: Pinned to `~=3.11.0`. Python 3.12+ is not supported due to dependency constraints.
  • Torch: CPU-only build on Linux (from `download.pytorch.org/whl/cpu`); macOS uses the standard PyTorch wheel.
  • Two runtimes: `SERVER_NAME=web` loads full settings; `SERVER_NAME=local_model` loads minimal settings without auth or most apps. A missing/wrong `SERVER_NAME` silently loads the wrong app set.
  • Config loading: `MAXKB_CONFIG_TYPE=ENV` reads from `MAXKB_*` env vars; otherwise loads YAML from `/opt/maxkb/conf`. The `.env` file uses ENV mode.
  • Sandbox: `installer/sandbox.c` is compiled to `sandbox.so` and loaded via `ctypes` for running untrusted Python in tools/nodes. Requires `gcc` at build time.
  • i18n: Supports `en_US`, `zh_CN`, `zh_Hant`. `.po` files in `apps/locales/`; must run `compilemessages` at build time.
  • Forced GC: Memory management runs periodic GC + `malloc_trim` every 3600s (configurable via `MAXKB_ENABLE_FORCE_GC`).

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment