Skip to content

利用 AI 大模型和自动化工作流,根据主题或关键词一键生成高清短视频。Generate HD short videos from a topic or keyword with an automated AI workflow.

feat(llm): add Claude Code provider using a Claude subscription

Tuan Nguyen4f469431ab8a
diff --git a/.gitignore b/.gitignore
index a997b7b2..641cebf5 100644
--- a/.gitignore
+++ b/.gitignore
@@ -42,3 +42,6 @@ htmlcov/
.codegraph
/docs/superpowers
.understand-anything
+
+# Claude Code 订阅令牌(docker compose 自动读取),禁止提交
+.env
diff --git a/Dockerfile.claude b/Dockerfile.claude
new file mode 100644
index 00000000..aa2d5e91
--- /dev/null
+++ b/Dockerfile.claude
@@ -0,0 +1,24 @@
+# Claude Code 变体镜像:在官方发布镜像的基础上安装 claude CLI。
+#
+# Claude 订阅(Pro / Max / Team)不签发 API Key,只有 Claude Code 官方客户端
+# 能使用订阅凭证,所以 `claude_code` Provider 依赖容器内存在可执行的 claude
+# CLI。这里复用发布镜像,避免重新安装 Python 依赖。
+FROM ghcr.io/harry0703/moneyprinterturbo:latest
+
+# CLI 版本固定,避免镜像重建时行为漂移;升级时改这里的版本号即可。
+ARG CLAUDE_CODE_VERSION=2.1.260
+ARG NODE_MAJOR=22
+
+# claude CLI 通过 npm 分发,发布镜像里没有 Node.js,需要先装 NodeSource 源。
+RUN set -eu; \
+ apt-get update; \
+ apt-get install -y --no-install-recommends ca-certificates curl gnupg; \
+ curl -fsSL "https://deb.nodesource.com/setup_${NODE_MAJOR}.x" | bash -; \
+ apt-get install -y --no-install-recommends nodejs; \
+ npm install -g "@anthropic-ai/claude-code@${CLAUDE_CODE_VERSION}"; \
+ npm cache clean --force; \
+ apt-get purge -y gnupg; \
+ apt-get autoremove -y; \
+ apt-get clean; \
+ rm -rf /var/lib/apt/lists/*; \
+ claude --version
diff --git a/app/models/llm_provider.py b/app/models/llm_provider.py
index 2430f2ac..dc6aea01 100644
--- a/app/models/llm_provider.py
+++ b/app/models/llm_provider.py
@@ -389,6 +389,23 @@ LLM_PROVIDER_REGISTRY = (
requires_api_key=False,
show_api_key=False,
),
+ # Claude 订阅(Pro / Max / Team)不签发 API Key,凭证只能由 Claude Code
+ # 官方客户端使用,因此这个 Provider 不走 HTTP 接口,而是调用本机已登录
+ # 的 claude CLI。模型名留空即沿用 CLI 当前的默认模型。
+ LLMProviderSpec(
+ "claude_code",
+ "Claude Code (Claude subscription)",
+ adapter="claude_code",
+ requires_api_key=False,
+ show_api_key=False,
+ requires_base_url=False,
+ show_base_url=False,
+ requires_model_name=False,
+ extra_fields=(
+ LLMProviderField("cli_path", "Claude CLI Path"),
+ LLMProviderField("timeout", "Timeout (seconds)", default_value="300"),
+ ),
+ ),
LLMProviderSpec(
"oneapi",
"OneAPI",
diff --git a/app/services/llm.py b/app/services/llm.py
index e29e5f40..30fc43d0 100644
--- a/app/services/llm.py
+++ b/app/services/llm.py
@@ -43,6 +43,19 @@ Generate a script for a video, depending on the subject of the video.
8. respond in the same language as the video subject.
""".strip()
+# Claude Code CLI 默认使用编码 agent 的系统提示词,其中大量约束与文案写作
+# 无关,会让脚本和关键词生成偏离要求,因此调用时整体替换掉。
+CLAUDE_CODE_SYSTEM_PROMPT = (
+ "You are a concise copywriter. Follow the user's instructions and output "
+ "format exactly, and output nothing else."
+)
+# 文案生成是一次纯文本请求,不需要任何工具。显式禁用可以避免 CLI 在容器里
+# 尝试读写文件或联网,从而让每次调用都是确定的单轮生成。
+CLAUDE_CODE_DISALLOWED_TOOLS = (
+ "Bash Read Write Edit NotebookEdit Glob Grep WebFetch WebSearch Task"
+)
+CLAUDE_CODE_DEFAULT_TIMEOUT = 300.0
+
def _normalize_text_response(content, llm_provider: str) -> str:
# 不同 LLM SDK 在异常或被拦截场景下,可能返回 None、空字符串,
@@ -355,6 +368,116 @@ def _generate_response(prompt: str, app_config=None) -> str:
f"[{llm_provider}] returned an empty response, please check your network connection and try again."
)
+ if adapter == "claude_code":
+ # Claude 订阅(Pro / Max / Team)不签发 API Key,其凭证只能由
+ # Claude Code 官方客户端自己使用。这里不直接请求 Anthropic API,
+ # 而是以 headless 模式调用本机已登录的 claude CLI(`claude -p`),
+ # 由 CLI 完成鉴权,脚本生成只消费它返回的文本。
+ import os
+ import shutil
+ import subprocess
+ import tempfile
+
+ configured_cli = (extra_values.get("cli_path") or "").strip() or "claude"
+ cli_path = shutil.which(configured_cli)
+ if not cli_path and os.path.isfile(configured_cli):
+ cli_path = configured_cli
+ if not cli_path:
+ raise ValueError(
+ f"{llm_provider}: claude CLI not found ('{configured_cli}'), "
+ f"install it in the runtime or set "
+ f"{provider.config_key('cli_path')} in the config.toml file."
+ )
+
+ configured_timeout = (extra_values.get("timeout") or "").strip()
+ try:
+ timeout_seconds = (
+ float(configured_timeout)
+ if configured_timeout
+ else CLAUDE_CODE_DEFAULT_TIMEOUT
+ )
+ except ValueError:
+ raise ValueError(
+ f"{llm_provider}: {provider.config_key('timeout')} must be a "
+ f"number of seconds, got '{configured_timeout}'."
+ )
+ if timeout_seconds <= 0:
+ raise ValueError(
+ f"{llm_provider}: {provider.config_key('timeout')} must be "
+ "greater than 0."
+ )
+
+ command = [
+ cli_path,
+ "-p",
+ prompt,
+ "--output-format",
+ "json",
+ "--system-prompt",
+ CLAUDE_CODE_SYSTEM_PROMPT,
+ "--disallowed-tools",
+ CLAUDE_CODE_DISALLOWED_TOOLS,
+ "--strict-mcp-config",
+ ]
+ # 模型名留空时沿用 CLI 自己的默认模型,避免这里硬编码的模型 ID
+ # 随订阅可用模型变化而失效。
+ if model_name:
+ command += ["--model", model_name]
+
+ logger.info(f"invoking claude cli, model: {model_name or 'cli default'}")
+ # CLI 会读取工作目录下的 CLAUDE.md 和项目设置,这些内容会污染
+ # 文案结果,因此固定在一个临时空目录中执行。
+ with tempfile.TemporaryDirectory() as work_dir:
+ try:
+ completed = subprocess.run(
+ command,
+ capture_output=True,
+ text=True,
+ timeout=timeout_seconds,
+ cwd=work_dir,
+ )
+ except subprocess.TimeoutExpired:
+ raise Exception(
+ f"[{llm_provider}] claude cli timed out after "
+ f"{timeout_seconds:.0f}s"
+ )
+
+ # 未登录、用量耗尽这类失败同样会返回 JSON(`is_error` 为真,
+ # `result` 是可读原因),只是退出码非 0。因此先解析 stdout,
+ # 只有在拿不到 JSON 时才回退到退出码和 stderr。
+ stdout = (completed.stdout or "").strip()
+ try:
+ payload = json.loads(stdout) if stdout else None
+ except json.JSONDecodeError:
+ payload = None
+
+ if payload is None:
+ detail = (completed.stderr or stdout or "").strip()
+ if completed.returncode != 0:
+ raise Exception(
+ f"[{llm_provider}] claude cli exited with code "
+ f"{completed.returncode}: {detail[:500]}"
+ )
+ raise Exception(
+ f'[{llm_provider}] returned an invalid response: "{detail[:500]}"'
+ )
+
+ if payload.get("is_error") or completed.returncode != 0:
+ reason = str(payload.get("result") or "").strip() or (
+ f"claude cli exited with code {completed.returncode}"
+ )
+ # 容器里无法执行交互式 /login,这里直接给出可用的鉴权方式。
+ if "login" in reason.lower():
+ reason += (
+ " (run `claude setup-token` on the host and pass the token "
+ "to the container as CLAUDE_CODE_OAUTH_TOKEN)"
+ )
+ raise Exception(
+ f'[{llm_provider}] returned an error response: "{reason[:500]}"'
+ )
+
+ return _normalize_text_response(payload.get("result"), llm_provider)
+
if adapter == "modelscope":
content = ""
client = OpenAI(
diff --git a/config.example.toml b/config.example.toml
index 11a80eec..40dec699 100644
--- a/config.example.toml
+++ b/config.example.toml
@@ -347,6 +347,20 @@ openrouter_model_name = ""
ollama_base_url = ""
ollama_model_name = ""
+# Claude Code (Claude Pro / Max / Team subscription).
+# Uses the locally installed, logged-in `claude` CLI in headless mode instead of
+# an API key, so no Anthropic API credit is needed. Requirements:
+# - the `claude` CLI must be installed in whatever runs MoneyPrinterTurbo
+# - it must be authenticated: interactively via `claude` on the host, or with
+# a long-lived token from `claude setup-token` exported as
+# CLAUDE_CODE_OAUTH_TOKEN (needed for Docker)
+# Leave model_name empty to use the CLI's current default model, or set one such
+# as "claude-opus-5" / "claude-sonnet-5". Leave cli_path empty to resolve
+# `claude` from PATH. Calls count against your Claude subscription usage limits.
+claude_code_model_name = ""
+claude_code_cli_path = ""
+claude_code_timeout = "300"
+
# OneAPI. Use the token, Base URL, and model ID from your OneAPI deployment.
# Project: https://github.com/songquanpeng/one-api
oneapi_api_key = ""
diff --git a/docker-compose.claude.yml b/docker-compose.claude.yml
new file mode 100644
index 00000000..c6b110b2
--- /dev/null
+++ b/docker-compose.claude.yml
@@ -0,0 +1,42 @@
+# 使用 Claude 订阅(Pro / Max / Team)作为 LLM Provider 的运行方式。
+#
+# 与 docker-compose.release.yml 的区别:
+# 1. 构建 Dockerfile.claude,容器内包含 claude CLI;
+# 2. 挂载整个项目目录,使 claude_code Provider 的代码生效;
+# 3. 注入 CLAUDE_CODE_OAUTH_TOKEN,容器内没有 keychain,CLI 只能用
+# `claude setup-token` 生成的长期令牌完成鉴权。
+#
+# 启动前先导出令牌:
+# export CLAUDE_CODE_OAUTH_TOKEN="$(claude setup-token)"
+# docker compose -f docker-compose.claude.yml up -d --build
+
+x-common-build: &common-build
+ context: .
+ dockerfile: Dockerfile.claude
+
+x-common-volumes: &common-volumes
+ - ./:/MoneyPrinterTurbo
+
+x-common-environment: &common-environment
+ # 未设置令牌时直接让 compose 报错,避免容器起来后才在生成阶段失败。
+ CLAUDE_CODE_OAUTH_TOKEN: ${CLAUDE_CODE_OAUTH_TOKEN:?run 'export CLAUDE_CODE_OAUTH_TOKEN="$(claude setup-token)"' first}
+
+services:
+ webui:
+ build: *common-build
+ container_name: "moneyprinterturbo-webui"
+ ports:
+ - "127.0.0.1:8501:8501"
+ command: [ "streamlit", "run", "./webui/Main.py", "--server.address=0.0.0.0", "--server.port=8501", "--browser.serverAddress=127.0.0.1", "--server.enableCORS=True", "--browser.gatherUsageStats=False", "--client.toolbarMode=minimal", "--logger.hideWelcomeMessage=True", "--server.showEmailPrompt=False" ]
+ volumes: *common-volumes
+ environment: *common-environment
+ restart: always
+ api:
+ build: *common-build
+ container_name: "moneyprinterturbo-api"
+ ports:
+ - "127.0.0.1:8080:8080"
+ command: [ "python3", "main.py" ]
+ volumes: *common-volumes
+ environment: *common-environment
+ restart: always
diff --git a/webui/i18n/en.json b/webui/i18n/en.json
index 42e4f0a4..5897d2c6 100644
--- a/webui/i18n/en.json
+++ b/webui/i18n/en.json
@@ -422,6 +422,7 @@
"llm_provider_endpoint.moonshot.global": "Global",
"llm_provider_authentication_error.moonshot": "Authentication failed. Make sure the API Key matches the selected Kimi platform. China uses platform.kimi.com with api.moonshot.cn; Global uses platform.kimi.ai with api.moonshot.ai. Current Base URL: {base_url}. Provider response: {error}",
"llm_provider_tips.ollama": "##### Ollama Configuration\n- **API Key**: not required\n- **Base Url**: usually `http://localhost:11434/v1` for local runs or `http://host.docker.internal:11434/v1` for Docker{docker_hint}\n- **Model Name**: required; run `ollama list` and enter an installed model, such as `qwen:7b`",
+ "llm_provider_tips.claude_code": "##### Claude Code Configuration\n- **API Key**: not required; the local `claude` CLI authenticates with your Claude subscription (Pro / Max / Team)\n- **Model Name**: optional; leave empty to use the CLI default, or set `claude-opus-5` / `claude-sonnet-5`\n- **Claude CLI Path**: optional; leave empty to resolve `claude` from PATH\n- Requires the CLI to be installed and logged in where MoneyPrinterTurbo runs. In Docker, pass a `claude setup-token` token as `CLAUDE_CODE_OAUTH_TOKEN`\n- Requests count against your Claude subscription usage limits, not API credit",
"llm_provider_tips.ollama.docker_hint": "\n > Container environment detected. If Base Url is empty, `http://host.docker.internal:11434/v1` is used by default.\n",
"llm_provider_tips.openai": "##### OpenAI Configuration\n- **API Key**: create one on the [OpenAI Platform]({api_key_url})\n- **Base Url**: defaults to `{default_base_url}`; enter another endpoint when using a compatible service\n- **Model Name**: defaults to `{default_model}`; you can also enter another model ID available to your account\n> Accessing the official service may require a network proxy in some regions",
"llm_provider_tips.anthropic": "##### Anthropic Claude Configuration\n- **API Key**: create one in the [Claude Console]({api_key_url})\n- **Base Url**: defaults to `{default_base_url}`, the OpenAI-compatible endpoint provided by Anthropic\n- **Model Name**: defaults to `{default_model}`; you can also enter another Claude model ID available to your account",
diff --git a/webui/i18n/zh.json b/webui/i18n/zh.json
index 8d261b5e..92957425 100644
--- a/webui/i18n/zh.json
+++ b/webui/i18n/zh.json
@@ -422,6 +422,7 @@
"llm_provider_endpoint.moonshot.global": "国际站",
"llm_provider_authentication_error.moonshot": "鉴权失败。请确认 API Key 与所选 Kimi 平台一致:中国站使用 platform.kimi.com 和 api.moonshot.cn,国际站使用 platform.kimi.ai 和 api.moonshot.ai。当前 Base URL:{base_url}。平台返回:{error}",
"llm_provider_tips.ollama": "##### Ollama 配置说明\n- **API Key**: 无需填写\n- **Base Url**: 本机运行时通常为 `http://localhost:11434/v1`;Docker 部署时通常为 `http://host.docker.internal:11434/v1`{docker_hint}\n- **Model Name**: 必填;运行 `ollama list` 查看本机已安装的模型,例如 `qwen:7b`",
+ "llm_provider_tips.claude_code": "##### Claude Code 配置说明\n- **API Key**:不需要;由本机 `claude` CLI 使用你的 Claude 订阅(Pro / Max / Team)完成鉴权\n- **Model Name**:可选;留空则使用 CLI 默认模型,也可填写 `claude-opus-5` / `claude-sonnet-5`\n- **Claude CLI Path**:可选;留空则从 PATH 中查找 `claude`\n- 运行 MoneyPrinterTurbo 的环境中必须已安装并登录 CLI;Docker 环境需将 `claude setup-token` 生成的令牌通过 `CLAUDE_CODE_OAUTH_TOKEN` 传入\n- 调用消耗的是 Claude 订阅额度,不消耗 API 余额",
"llm_provider_tips.ollama.docker_hint": "\n > 检测到容器环境,未配置 Base Url 时会默认使用 `http://host.docker.internal:11434/v1`\n",
"llm_provider_tips.openai": "##### OpenAI 配置说明\n- **API Key**: 在 [OpenAI Platform]({api_key_url}) 创建\n- **Base Url**: 默认 `{default_base_url}`;使用兼容服务时可填写对应地址\n- **Model Name**: 默认 `{default_model}`;也可以填写当前账号支持的其它模型 ID\n> 部分地区访问官方服务时可能需要配置网络代理",
"llm_provider_tips.anthropic": "##### Anthropic Claude 配置说明\n- **API Key**: 在 [Claude Console]({api_key_url}) 创建\n- **Base Url**: 默认 `{default_base_url}`,即 Anthropic 提供的 OpenAI 兼容端点\n- **Model Name**: 默认 `{default_model}`;也可以填写当前账号支持的其它 Claude 模型 ID",