Skip to content

PRINTFILM: AI short-video marketing and AI short-drama creation platform

Support any OpenAI-compatible text model via channel sync.

yi7170d677356f
diff --git a/backend/.env.example b/backend/.env.example
index 6039ffa..5efd660 100644
--- a/backend/.env.example
+++ b/backend/.env.example
@@ -22,7 +22,16 @@ PUBLIC_BASE_URL=http://192.168.110.88:8000
ARK_MOCK=false
ARK_API_KEY=replace-me
-# 文字模型 Kimi(OpenAI 兼容,对齐 manju;生图/视频仍走方舟 ARK_*)
+# 文字模型:任意 OpenAI 兼容上游(生图/视频仍走方舟 ARK_*)
+# 示例 A — Kimi:
+# OPENAI_API_KEY=sk-xxx
+# OPENAI_BASE_URL=https://api.moonshot.cn/v1
+# MODEL_LLM=kimi-k2.6
+# 示例 B — DeepSeek:
+# OPENAI_API_KEY=sk-xxx
+# OPENAI_BASE_URL=https://api.deepseek.com
+# MODEL_LLM=deepseek-chat
+# 也可在管理后台「模型渠道」填写 Base URL / Key / models,默认文本模型会随渠道自动同步
OPENAI_API_KEY=replace-me
OPENAI_BASE_URL=https://api.moonshot.cn/v1
MODEL_LLM=kimi-k2.6
diff --git a/backend/app/config.py b/backend/app/config.py
index 5135801..db81f8d 100644
--- a/backend/app/config.py
+++ b/backend/app/config.py
@@ -24,9 +24,10 @@ class Settings(BaseSettings):
ark_api_key: str = ""
ark_base_url: str = "https://ark.cn-beijing.volces.com/api/v3"
- # 文字模型(Kimi 等 OpenAI 兼容 API,对齐 manju OPENAI_*)
+ # 文字模型(任意 OpenAI 兼容 API:DeepSeek / Kimi / OpenAI 等)
openai_api_key: str = ""
openai_base_url: str = ""
+ # 默认示例为 kimi;实际以后台渠道 models + 默认定稿为准,可改为 deepseek-chat 等
model_llm: str = "kimi-k2.6"
model_image: str = "doubao-seedream-5-0-260128"
# Seedream 4.5 接入点(可选;未配则回退 model_image)
diff --git a/backend/app/services/llm_client.py b/backend/app/services/llm_client.py
index ebfc14f..8f0bca4 100644
--- a/backend/app/services/llm_client.py
+++ b/backend/app/services/llm_client.py
@@ -1,4 +1,4 @@
-"""OpenAI 兼容文字模型客户端(对齐 manju agents/llm.ts)。"""
+"""OpenAI 兼容文字模型客户端(任意兼容上游:Kimi / DeepSeek / OpenAI 等)。"""
from __future__ import annotations
@@ -12,9 +12,6 @@ from app.services.logical_model_router import resolve_logical_model, resolve_log
logger = logging.getLogger(__name__)
-# DEFAULT_LLM_MODEL kimi-k2.6:关闭 thinking 后结构化长文本更快
-DEFAULT_LLM_MODEL = "kimi-k2.6"
-
# DEFAULT_MAX_TOKENS 分集正文等结构化输出需要足够 completion 空间
DEFAULT_MAX_TOKENS = 32768
@@ -29,8 +26,8 @@ def resolve_llm_api_key() -> str:
if not key:
raise LlmUnavailableError(
"未配置 OPENAI_API_KEY,无法调用文字模型。"
- "请在 backend/.env 设置 OPENAI_API_KEY、OPENAI_BASE_URL,"
- f"并将 MODEL_LLM 设为 {DEFAULT_LLM_MODEL}(或你的 Kimi 接入点)。"
+ "请在后台渠道或 backend/.env 配置 OpenAI 兼容 Key、Base URL,"
+ "并将 MODEL_LLM / 渠道 models 设为该上游的模型 ID(如 deepseek-chat、kimi-k2.6)。"
)
return key
@@ -43,9 +40,10 @@ def resolve_llm_base_url() -> str:
return "https://api.openai.com/v1"
-# kimi-k2.6 需关闭 thinking,否则 token 耗在 reasoning_content、content 为空
+# kimi / deepseek-v4 默认 thinking 会占满 token、content 常为空;结构化产出统一关闭
def _llm_extra_body(model: str) -> dict[str, Any]:
- if (model or "").strip().lower().startswith("kimi"):
+ mid = (model or "").strip().lower()
+ if mid.startswith("kimi") or mid.startswith("deepseek"):
return {"thinking": {"type": "disabled"}}
return {}
@@ -79,13 +77,18 @@ async def chat_completions(
route = resolve_logical_model("text", logical_id)
if route:
api_key = route.api_key
- model = (route.upstream_model or DEFAULT_LLM_MODEL).strip() or DEFAULT_LLM_MODEL
+ model = (route.upstream_model or "").strip()
base = route.base_url.rstrip("/") or resolve_llm_base_url()
else:
api_key = resolve_llm_api_key()
- model = (settings.model_llm or DEFAULT_LLM_MODEL).strip() or DEFAULT_LLM_MODEL
+ model = (settings.model_llm or "").strip()
base = resolve_llm_base_url()
- # kimi-k2.6 仅允许 temperature=0.6,其它值会 400
+ if not model:
+ raise LlmUnavailableError(
+ "未解析到可用文字模型。请在后台启用 OpenAI 兼容渠道,"
+ "并在渠道 models / 默认文本模型中填写上游模型 ID。"
+ )
+ # kimi 系列仅允许 temperature=0.6,其它值会 400
effective_temperature = 0.6 if model.lower().startswith("kimi") else temperature
payload: dict[str, Any] = {
diff --git a/backend/app/services/logical_model_router.py b/backend/app/services/logical_model_router.py
index 12e088c..27ea890 100644
--- a/backend/app/services/logical_model_router.py
+++ b/backend/app/services/logical_model_router.py
@@ -7,13 +7,41 @@ from app.services.model_routing_config import (
channel_connection_ready,
channel_supports_model,
infer_model_capability,
- normalize_model_name,
resolve_channel_model_capability,
- resolve_logical_model_config,
)
from app.services.model_settings import get_routing_snapshot
+# 解析某逻辑模型的可用路由
+def _routes_for_logical_model(
+ logical: LogicalModel,
+ capability: LogicalModelCapability,
+ channels: list[SystemModelChannel],
+ *,
+ preferred_channel_id: str = "",
+) -> list[ResolvedModelRoute]:
+ bindings = sorted(
+ [binding for binding in logical.bindings if binding.enabled],
+ key=lambda binding: (
+ 0 if preferred_channel_id and binding.channel_id == preferred_channel_id else 1,
+ binding.priority,
+ -(binding.weight or 100),
+ binding.id,
+ ),
+ )
+ routes: list[ResolvedModelRoute] = []
+ for binding in bindings:
+ channel = next((item for item in channels if item.id == binding.channel_id), None)
+ if not channel or not channel_connection_ready(channel):
+ continue
+ if not channel_supports_model(channel, binding.upstream_model):
+ continue
+ route = _build_route(capability, logical.id, binding.upstream_model, channel)
+ if route:
+ routes.append(route)
+ return routes
+
+
# 解析逻辑模型到运行时路由(含 failover 候选列表)
def resolve_logical_model_candidates(
capability: LogicalModelCapability,
@@ -21,48 +49,53 @@ def resolve_logical_model_candidates(
*,
preferred_channel_id: str = "",
) -> list[ResolvedModelRoute]:
+ """按请求 ID 解析;不可用时回落到同能力任一可解析逻辑模型(通用模型)。"""
snapshot = get_routing_snapshot()
requested = (requested_model_id or "").strip()
if not requested:
requested = _default_model_id(snapshot.default_models, capability)
- if not requested:
- return []
- logical = next(
- (
- model
- for model in snapshot.logical_models
- if model.enabled
- and model.capability == capability
- and model.id.lower() == requested.lower()
- ),
- None,
- )
- if logical:
- bindings = sorted(
- [binding for binding in logical.bindings if binding.enabled],
- key=lambda binding: (
- 0 if preferred_channel_id and binding.channel_id == preferred_channel_id else 1,
- binding.priority,
- -(binding.weight or 100),
- binding.id,
+ if requested:
+ logical = next(
+ (
+ model
+ for model in snapshot.logical_models
+ if model.enabled
+ and model.capability == capability
+ and model.id.lower() == requested.lower()
),
+ None,
)
- routes: list[ResolvedModelRoute] = []
- for binding in bindings:
- channel = next((item for item in snapshot.channels if item.id == binding.channel_id), None)
- if not channel or not channel_connection_ready(channel):
- continue
- if not channel_supports_model(channel, binding.upstream_model):
- continue
- route = _build_route(capability, logical.id, binding.upstream_model, channel)
- if route:
- routes.append(route)
- return routes
+ if logical:
+ routes = _routes_for_logical_model(
+ logical,
+ capability,
+ snapshot.channels,
+ preferred_channel_id=preferred_channel_id,
+ )
+ if routes:
+ return routes
+
+ # 默认/请求模型失效时,回落到同能力第一个可解析模型(DeepSeek / Kimi / 其它兼容均可)
+ for model in snapshot.logical_models:
+ if not model.enabled or model.capability != capability:
+ continue
+ if requested and model.id.lower() == requested.lower():
+ continue
+ routes = _routes_for_logical_model(
+ model,
+ capability,
+ snapshot.channels,
+ preferred_channel_id=preferred_channel_id,
+ )
+ if routes:
+ return routes
if snapshot.logical_models:
return []
+ if not requested:
+ return []
ordered = snapshot.channels
if preferred_channel_id:
ordered = [
diff --git a/backend/app/services/model_settings.py b/backend/app/services/model_settings.py
index 33e9791..83e3ed9 100644
--- a/backend/app/services/model_settings.py
+++ b/backend/app/services/model_settings.py
@@ -349,6 +349,7 @@ def _effective_flat(stored: dict[str, Any] | None) -> dict[str, Any]:
async def _compose_runtime_state(db: AsyncSession) -> tuple[list[SystemModelChannel], list[LogicalModel], DefaultModels, dict[str, Any], AppSettings]:
+ """组装运行时路由:始终按渠道 models 同步逻辑模型,默认文字模型随可用上游回落。"""
app_row = await _get_or_create_app_row(db)
await _ensure_bootstrapped_channels(db)
channels = await _load_channels(db, runtime=True)
@@ -359,12 +360,31 @@ async def _compose_runtime_state(db: AsyncSession) -> tuple[list[SystemModelChan
logical_models, default_models = _bootstrap_logical_from_channels(
[_channel_row_to_admin(row) for row in (await db.execute(select(SystemModelChannelRow))).scalars().all()]
)
+ # 渠道 models 变更后,丢弃失效绑定并补齐新上游(支持任意 OpenAI 兼容模型)
+ logical_models = synchronize_logical_models_with_channels(logical_models, channels)
+ default_models = normalize_default_models(default_models, logical_models, channels)
flat = _effective_flat(_decrypt_flat_config(config))
+ if default_models.text_model:
+ flat["model_llm"] = default_models.text_model
return channels, logical_models, default_models, flat, app_row
async def load_model_settings_cache(db: AsyncSession) -> None:
- channels, logical_models, default_models, flat, _ = await _compose_runtime_state(db)
+ """加载路由快照;若与渠道不同步则回写 healed 配置,避免默认仍钉死旧模型名。"""
+ channels, logical_models, default_models, flat, app_row = await _compose_runtime_state(db)
+ config = dict(app_row.config_json or {})
+ old_ids = {(item or {}).get("id") for item in (config.get("logical_models") or [])}
+ new_ids = {model.id for model in logical_models}
+ old_defaults = default_models_from_dict(config.get("default_models"))
+ if old_ids != new_ids or old_defaults != default_models:
+ config["logical_models"] = [model.model_dump() for model in logical_models]
+ config["default_models"] = default_models_to_dict(default_models)
+ flat_cfg = dict(config.get("flat") or {})
+ if default_models.text_model:
+ flat_cfg["model_llm"] = default_models.text_model
+ config["flat"] = flat_cfg
+ app_row.config_json = config
+ await db.commit()
_refresh_routing_snapshot(channels, logical_models, default_models)
_refresh_overlay({"flat": flat})
reload_settings()
@@ -556,11 +576,13 @@ async def patch_admin_routing_settings(
logical_models = body.logical_models
applied.append("logical_models")
elif body.system_channels is not None:
- synced = synchronize_logical_models_with_channels(logical_models, channels_after)
bootstrapped, _ = _bootstrap_logical_from_channels(channels_after)
alias_ids = {"seedream-5.0", "seedream-4.5", "seedance-2.5"}
extras = [model for model in bootstrapped if model.id in alias_ids]
- logical_models = synchronize_logical_models_with_channels(synced + extras, channels_after)
+ logical_models = logical_models + extras
+
+ # 无论前端是否提交逻辑模型,最终都以渠道 models 为准同步(通用 OpenAI 兼容)
+ logical_models = synchronize_logical_models_with_channels(logical_models, channels_after)
defaults = default_models_from_dict(config.get("default_models"))
if body.default_models is not None:
diff --git a/backend/tests/test_generic_text_model_routing.py b/backend/tests/test_generic_text_model_routing.py
new file mode 100644
index 0000000..d72fb28
--- /dev/null
+++ b/backend/tests/test_generic_text_model_routing.py
@@ -0,0 +1,80 @@
+"""文字模型路由:渠道 models 变更后默认同步到通用 OpenAI 兼容模型。"""
+
+from app.schemas_routing import DefaultModels, LogicalModel, LogicalModelBinding, SystemModelChannel
+from app.services.model_routing_config import (
+ normalize_default_models,
+ synchronize_logical_models_with_channels,
+)
+
+
+def _channel(**kwargs) -> SystemModelChannel:
+ return SystemModelChannel(
+ id=kwargs.get("id", "openai-default"),
+ name=kwargs.get("name", "OpenAI 兼容 LLM"),
+ base_url=kwargs.get("base_url", "https://api.deepseek.com"),
+ api_key=kwargs.get("api_key", "sk-test"),
+ has_api_key=True,
+ api_format="openai",
+ protocol="openai",
+ models=kwargs.get("models", ["deepseek-chat"]),
+ enabled=True,
+ sort_order=0,
+ )
+
+
+def test_sync_drops_stale_kimi_when_channel_switches_to_deepseek():
+ """渠道改为 DeepSeek 后,逻辑模型与默认文本模型应落到 deepseek-chat。"""
+ channels = [_channel(models=["deepseek-chat"])]
+ stale = [
+ LogicalModel(
+ id="kimi-k2.6",
+ name="kimi-k2.6",
+ capability="text",
+ enabled=True,
+ bindings=[
+ LogicalModelBinding(
+ id="openai-default:kimi-k2.6",
+ channel_id="openai-default",
+ upstream_model="kimi-k2.6",
+ enabled=True,
+ priority=1,
+ )
+ ],
+ )
+ ]
+ synced = synchronize_logical_models_with_channels(stale, channels)
+ defaults = normalize_default_models(
+ DefaultModels(text_model="kimi-k2.6"),
+ synced,
+ channels,
+ )
+ assert [m.id for m in synced] == ["deepseek-chat"]
+ assert defaults.text_model == "deepseek-chat"
+
+
+def test_sync_keeps_binding_prefs_for_matching_upstream():
+ """同名上游保留原绑定 priority / enabled。"""
+ channels = [_channel(models=["deepseek-chat"])]
+ existing = [
+ LogicalModel(
+ id="deepseek-chat",
+ name="DeepSeek Chat",
+ capability="text",
+ enabled=True,
+ bindings=[
+ LogicalModelBinding(
+ id="openai-default:deepseek-chat",
+ channel_id="openai-default",
+ upstream_model="deepseek-chat",
+ enabled=True,
+ priority=3,
+ weight=80,
+ )
+ ],
+ )
+ ]
+ synced = synchronize_logical_models_with_channels(existing, channels)
+ assert len(synced) == 1
+ assert synced[0].name == "DeepSeek Chat"
+ assert synced[0].bindings[0].priority == 3
+ assert synced[0].bindings[0].weight == 80